package com.probox.common.entity.service.order.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.probox.activity.api.domain.*;
import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.constant.Constants;
import com.probox.common.core.constant.HttpStatus;
import com.probox.common.core.constant.MessageConstants;
import com.probox.common.core.domain.WeChatInfomationOrder;
import com.probox.common.core.domain.WechatInfomation;
import com.probox.common.core.enums.*;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.utils.DateUtils;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.core.utils.money.MoneyUtils;
import com.probox.common.core.utils.sql.SqlUtil;
import com.probox.common.core.web.page.PageDomain;
import com.probox.common.core.web.page.TableDataInfo;
import com.probox.common.core.web.page.TableSupport;

import com.probox.common.entity.domain.customer.*;
import com.probox.common.entity.domain.order.*;
import com.probox.common.entity.domain.order.vo.OrderMergeDetailVo;
import com.probox.common.entity.domain.order.vo.OrderSettlementVo;
import com.probox.common.entity.domain.order.vo.ShopCartVo;
import com.probox.common.entity.domain.platfom.PlatformStore;
import com.probox.common.entity.domain.product.ProductInfo;
import com.probox.common.entity.domain.recharge.RechargeRecord;
import com.probox.common.entity.domain.recharge.RechargeRecordRights;
import com.probox.common.entity.mapper.order.OrderInfoMapper;

import com.probox.common.entity.service.customer.*;
import com.probox.common.entity.service.order.*;
import com.probox.common.entity.service.platfom.IPlatformFreightService;
import com.probox.common.entity.service.platfom.IPlatformGeneralsettingsService;
import com.probox.common.entity.service.platfom.IPlatformStoreService;
import com.probox.common.entity.service.product.IProductCommentService;
import com.probox.common.entity.service.product.IProductInfoService;
import com.probox.common.entity.service.recharge.IRechargeRecordRightsService;
import com.probox.common.entity.service.recharge.IRechargeRecordService;
import com.probox.common.entity.service.system.ISysUserService;
import com.probox.common.entity.vo.customer.RechargeRightItem;
import com.probox.common.entity.vo.proboxService.BalanceItemVo;
import com.probox.common.entity.vo.system.WorkOrderDetailVo;
import com.probox.common.entity.vo.system.WorkOrderVo;
import com.probox.common.redis.service.RedisService;

import com.probox.customer.api.domain.*;
import com.probox.order.api.domain.*;
import com.probox.order.api.utils.WechatV3Payment;
import com.probox.platform.api.domain.PlatformFreightVo;
import com.probox.platform.api.domain.PlatformGeneralsettingsVo;
import com.probox.product.api.domain.*;
import com.probox.supplier.api.domain.SupplierVo;
import com.probox.systemApi.domain.SysUser;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 订单子Service业务层处理
 *
 * @author usoft
 * @date 2021-05-27
 */
@Service
@Transactional
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {

    //订单限制用户的操作间隙
    private static final Long user_operator_limit_time = 1L;
    private static final Long user_operator_limit = 1L;
    //用户操作订单的缓存
    private static final String user_operator_limit_key = CachePrefix.PRE_GLOABLE + "user_operator_order_limit_";
    private static final String order_no_key = CachePrefix.PRE_GLOABLE + "order_no_";

    //延迟收货操作限制
    private static final int ONEMONTH = 30 * 24 * 60 * 60;
    private static final String user_delay_order = CachePrefix.PRE_GLOABLE + "user_delay_order_";

    private final Logger logger = LoggerFactory.getLogger(OrderInfoServiceImpl.class);

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private IOrderInfoItemService itemService;

    @Autowired
    private IOrderInvoiceService invoiceService;

    @Autowired
    private IOrderShipDeliverService deliverService;

    @Autowired
    private IOrderShopCartService shopCartService;

    @Autowired
    private ICustomerInfoService iCustomerInfoService;


    @Autowired
    private IOrderInfoParentService orderInfoParentService;

    @Autowired
    private RedisService redisService;


    @Autowired
    private IOrderPayInfoService orderPayInfoService;



    @Autowired
    private IOrderPostSaleService postSaleService;

    @Autowired
    private IOrderComplaintService complaintService;

    @Autowired
    private IOrderShipAutoService shipAutoService;

    @Autowired
    private IOrderTraceService orderTraceService;

    @Autowired
    private IOrderRechargeService rechargeService;


    @Autowired
    private IPlatformFreightService iPlatformFreightService;

    @Autowired
    private IProductInfoService iProductInfoService;

    @Autowired
    private IProductCommentService iProductCommentService;

    @Autowired
    private IPlatformGeneralsettingsService platformGeneralsettingsService;


    @Autowired
    private ICustomerFundService iCustomerFundService;

    @Autowired
    private ICustomerAddressService iCustomerAddressService;

    @Autowired
    private ICustomerInvoiceService iCustomerInvoiceService;

    @Autowired
    private ICustomerLevelService iCustomerLevelService;

    @Autowired
    private ICustomerLevelInfoService customerLevelInfoService;

    @Autowired
    private ICustomerPrivilegeService customerPrivilegeService;

    @Autowired
    private ISysUserService sysUserService;





    @Autowired
    private IPlatformStoreService platformStoreService;

    @Autowired
    private ICustomerFundStoreService customerFundStoreService;

    @Autowired
    private IOrderInfoItemPayService orderInfoItemPayService;

    @Autowired
    private IRechargeInfoService rechargeInfoService;

    @Autowired
    private IRechargeRecordService rechargeRecordService;


    @Autowired
    private IOrderInfoShareService orderInfoShareService;

    @Autowired
    private IRechargeRecordRightsService rechargeRecordRightsService;

    @Autowired
    private ICustomerHiddenLabelService customerHiddenLabelService;

    /**
     * 订单开票中心
     *
     * @param info
     * @return
     */
    @Override
    public List<OrderInfo> selectListByInvoice(OrderInfo info) {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_status", OrderStatusEnum.effect.getKey());
        queryWrapper.eq("pay_status", PayStatusEnum.paid.getKey());
        queryWrapper.isNotNull("INVOICE_UID");
        if (StringUtils.isNotEmpty(info.getCustomerName())) {
            queryWrapper.like("customer_name", info.getCustomerName());
        }
        if (StringUtils.isNotEmpty(info.getOrderNo())) {
            queryWrapper.like("order_no", info.getOrderNo());
        }
        if (StringUtils.isNotEmpty(info.getInvoiceStatus())) {
            queryWrapper.eq("INVOICE_STATUS", info.getInvoiceStatus());
        }

        if (ObjectUtil.isNotEmpty(info.getStoreId())) {
            queryWrapper.eq("STORE_ID", info.getStoreId());
        }
        return orderInfoMapper.selectList(queryWrapper);
    }

    /**
     * 收款接口
     */
    @Override
    public boolean collection(OrderInfo info) {
        String limit = CachePrefix.PRE_GLOABLE+"collection_"+SecurityUtils.getUserId();
        if (redisService.incr(limit,3,TimeUnit.SECONDS)>1){
            throw new BaseException("收款中，请稍后！");
        }
        OrderInfo orderInfo = this.getById(info.getOrderUid());
        if (ObjectUtil.isEmpty(orderInfo)) throw new BaseException("订单不存在！");
        if (PayStatusEnum.paid.getKey().equals(orderInfo.getPayStatus())) {
            throw new BaseException("用户已支付！");
        }
        if ("1".equals(info.getDiscount())){

        }else{
            if (info.getPayAmount() == null || info.getPayAmount().longValue() != orderInfo.getPayAmount()) {
                throw new BaseException("收款金额必须等于付款金额！");
            }
        }
        if (info.getRemark() != null){
            if (orderInfo.getRemark() == null){
                orderInfo.setRemark(info.getRemark());
            }else{
                orderInfo.setRemark(orderInfo.getRemark()+";"+info.getRemark());
            }
        }

        Double rate = 1.0;
        if (StringUtils.isEmpty(info.getPayMethod())) {
            orderInfo.setPayMethod(PayMethodEnum.cashPayment.getKey());
        }else{
            orderInfo.setPayMethod(info.getPayMethod());
        }
        orderInfo.setPayStatus(PayStatusEnum.paid.getKey());
        orderInfo.setPayAmount(info.getPayAmount());
        orderInfo.setPayTime(DateUtil.date());
        orderInfo.setProfitSharing(ProfitSharingEnum.N.toString());

        orderInfo.setSendStatus(SendStatusEnum.receive.getKey());
        orderInfo.setSendTime(orderInfo.getPayTime());
        orderInfo.setOrderPackStatus(PackStatusEnum.voted.getKey());
        orderInfo.setReceiveTime(orderInfo.getPayTime());
        orderInfo.setCommentStatus(CommentStatusEnum.comment.getKey());
        boolean rst = this.saveOrUpdate(orderInfo);
        if (orderInfo.getPayAmount().longValue() != orderInfo.getOrderAmount()){
            BigDecimal bg = new BigDecimal(orderInfo.getPayAmount()*rate/orderInfo.getOrderAmount()*rate);
            rate = bg.setScale(4, RoundingMode.HALF_UP).doubleValue();
        }
        OrderInfoParent parent = orderInfoParentService.getOrderInfo(orderInfo.getParentOrderNo());
        parent.setPayAmount(orderInfo.getPayAmount());
        parent.setPayStatus(orderInfo.getPayStatus());
        parent.setPayTime(orderInfo.getPayTime());
        orderInfoParentService.updateById(parent);
        List<OrderInfoItem> items = itemService.selectByOrderId(orderInfo.getOrderUid());
        if (items.size()==1){
            OrderInfoItem item = items.get(0);
            item.setPayAmount(orderInfo.getPayAmount());
            itemService.updateById(item);
        }else{
            Long payTotal = orderInfo.getPayAmount();
            for(OrderInfoItem item:items){
                Long pay = new BigDecimal(item.getPayAmount()*rate).longValue();
                if (pay>payTotal){
                    pay = payTotal;
                }
                item.setPayAmount(pay);
                payTotal = payTotal-pay;
                itemService.updateById(item);
            }
        }
        updateProductData(items);
        orderInfo.setOrderInfoItemList(items);
        //扣余额，积分等
        //deductionCustomerFund(parent, items);
        parent.setOrderInfoList(new ArrayList<>());
        parent.getOrderInfoList().add(orderInfo);

        customerProfit(parent, null);

        //销量操作日志
        if (ObjectUtil.isNotEmpty(items)) {
            for (OrderInfoItem item : items) {
                sendLogMsg(ProductOptType.buy.getKey(), parent.getPlatformId(), parent.getCustomerId(), item.getOrderType(), item.getProUid(), item.getItemNumber());
            }
        }

        if (orderInfo.getStoreId() != null) {
            PlatformStore store = platformStoreService.getById(orderInfo.getStoreId());
            if (store != null) {
                customerHiddenLabelService.addOrUpdateLabel(orderInfo.getCustomerUid(), OrderTypeEnum.store.getKey(), orderInfo.getStoreId(), store.getStoreName());
            }
        }

        return rst;
    }


    @Override
    public boolean renGongDaZhe(OrderInfo info) {
        String limit = CachePrefix.PRE_GLOABLE+"dazhe_"+SecurityUtils.getUserId();
        if (redisService.incr(limit,3,TimeUnit.SECONDS)>1){
            throw new BaseException("打折中，请稍后！");
        }
        OrderInfo orderInfo = this.getById(info.getOrderUid());
        if (ObjectUtil.isEmpty(orderInfo)) throw new BaseException("订单不存在！");
        if (PayStatusEnum.paid.getKey().equals(orderInfo.getPayStatus())) {
            throw new BaseException("用户已支付！");
        }

        if (info.getPayAmount() == null) {
            throw new BaseException("收款金额不能为空！");
        }
        if (info.getPayAmount().longValue() < 0) {
            throw new BaseException("收款金额不能小于0！");
        }
        if (info.getPayAmount().longValue()>orderInfo.getOrderAmount()){
            throw new BaseException("折后金额不能大于订单金额！");
        }
        if (orderInfo.getRenGongMoney() != null && orderInfo.getRenGongMoney().longValue()>0){
            throw new BaseException("订单不允许重复修改折后金额！");
        }
        if (info.getRemark() != null){
            if (orderInfo.getRemark() == null){
                orderInfo.setRemark(info.getRemark());
            }else{
                orderInfo.setRemark(orderInfo.getRemark()+";"+info.getRemark());
            }
        }

        Double rate = 1.0;
        long orderAmount = orderInfo.getOrderAmount().longValue();
        orderInfo.setRenGongMoney(info.getPayAmount());
        orderInfo.setProfitSharing(ProfitSharingEnum.N.toString());

        boolean rst = this.saveOrUpdate(orderInfo);
        if (orderAmount != orderInfo.getRenGongMoney()){
            BigDecimal bg = new BigDecimal(orderInfo.getRenGongMoney()*rate/orderAmount*rate);
            rate = bg.setScale(4, RoundingMode.HALF_UP).doubleValue();
        }

        List<OrderInfoItem> items = itemService.selectByOrderId(orderInfo.getOrderUid());
        if (items.size()==1){
            OrderInfoItem item = items.get(0);
            item.setItemAmount(orderInfo.getRenGongMoney());
            item.setPayAmount(0L);
            item.setPayByBalance(0L);
            item.setPayByRedBag(0L);
            item.setPayByScore(0L);
            itemService.updateById(item);
        }else{
            int size = items.size();
            int j = 0;
            Long payTotal = orderInfo.getRenGongMoney();
            for(OrderInfoItem item:items){
                Long pay = new BigDecimal(item.getItemAmount()*rate).longValue();
                if (pay>payTotal){
                    pay = payTotal;
                }
                if (j+1==size){
                    pay = payTotal;
                }
                item.setItemAmount(pay);
                item.setPayAmount(0L);
                item.setPayByBalance(0L);
                item.setPayByRedBag(0L);
                item.setPayByScore(0L);
                payTotal = payTotal-pay;
                itemService.updateById(item);
                j++;
            }
        }
        return rst;
    }

    /**
     * 查询订单详情
     *
     * @param orderId
     * @return
     */
    @Override
    public WorkOrderDetailVo getWorkOrderDetailVo(Long orderId) {
        OrderInfo orderInfo = this.getById(orderId);
        if (ObjectUtil.isEmpty(orderInfo)) throw new BaseException("订单不存在！");
        WorkOrderDetailVo vo = new WorkOrderDetailVo();
        vo.setOrderStatus(orderInfo.getOrderStatusName());
        vo.setOrderNo(orderInfo.getOrderNo());
        vo.setCreateTime(orderInfo.getCreateTime());
        vo.setRemark(orderInfo.getRemark());
        vo.setPayStatus(orderInfo.getPayStatus());
        vo.setOrderNo(orderInfo.getOrderNo());
        vo.setOrderAmount(orderInfo.getOrderAmountStr());
        vo.setDiscountAmount(orderInfo.getDiscountAmountStr());
        vo.setPayAmount(orderInfo.getPayAmountStr());
        vo.setPayBalance(orderInfo.getPayByBalanceStr());
        vo.setPayRedBag(orderInfo.getPayByRedBagStr());
        vo.setSkDate(orderInfo.getPayTime());
        vo.setReGongMoney(orderInfo.getReGongMoneyStr());
        vo.setCreateName(orderInfo.getCreateName());
        /**
         *
         * 查询客户
         */
        CustomerInfo customerInfo = iCustomerInfoService.getById(orderInfo.getCustomerUid());
        if (ObjectUtil.isNotEmpty(customerInfo)) {
            vo.setCustomerName(customerInfo.getCustomerName());
            vo.setSex(customerInfo.getSex());
            vo.setLevelName(customerLevelInfoService.getLevelNameByUid(customerInfo.getCustomerUid()));
            vo.setPhone(customerInfo.getPhone());
            vo.setCustomerImage(customerInfo.getHeadImage());
        }
        vo.setList(itemService.getByOrderUid(orderInfo.getOrderUid()));
        PlatformStore platformStore = platformStoreService.getById(orderInfo.getStoreId());
        if (ObjectUtil.isNotEmpty(platformStore)) {
            vo.setStoreName(platformStore.getStoreName());
        }
        return vo;
    }

    /**
     * 帮客户在后台创建菜单
     *
     * @param vo
     */
    @Override
    public OrderInfo createOrderByPC(WorkOrderVo vo) {
        if (vo.getStoreId() == null) throw new BaseException("没有门店 无法创建");
        if (CollectionUtil.isEmpty(vo.getList())) throw new BaseException("请选择项目/套餐卡");

        CustomerInfo customerInfo = iCustomerInfoService.getById(vo.getCustomerUid());
        if (ObjectUtil.isEmpty(customerInfo)) throw new BaseException("客户不存在");

        logger.info("=================开始创建支付订单===================");


        OrderInfo info = new OrderInfo();
        info.setPlatformUid(SecurityUtils.getPlatformId());
        info.setOrderType(OrderTypeEnum.serviceCard.getKey());
        info.setOrderNo(createOrderNo());

        info.setCreateName(SecurityUtils.getUsername());
        info.setCreateUid(SecurityUtils.getUserId());
        info.setStoreId(vo.getStoreId());
        /**
         * 查询客户信息
         */

        SysUser user = sysUserService.selectUserById(SecurityUtils.getUserId());
        info.setCustomerName(customerInfo.getCustomerName());
        info.setCustomerUid(customerInfo.getCustomerUid());
        info.setPhone(customerInfo.getPhone());
        info.setOrderStatus(DataStatus.valid.getKey());
        info.setPayStatus(PayStatusEnum.unpaid.getKey());
        info.setPlatSource(PlatSourceEnum.web.getKey());
        /**
         * 先处理金银币
         */
        info.setPayByBalance(0L);
        info.setPayByScore(0L);
        info.setPayByRedBag(0L);

        /**
         * 处理各种价格
         */
        info.setOrderAmount(MoneyUtils.changeY2F2(vo.getCountPrice()));
        info.setFreightAmount(0L);
        info.setCreateTime(DateUtil.date());
        info.setUpdateTime(DateUtil.date());
        info.setUpdateUser(SecurityUtils.getUserId());
        info.setUpdateUserName(SecurityUtils.getUsername());

//        SecurityUtils.getCustomerClientIp();
        info.setInvoiceStatus(InvoiceStatusEnum.unInvoice.getKey());
        info.setSendStatus(SendStatusEnum.unShip.getKey());
        //info.setStoreId(user.getStoreId());
        info.setIsShared("0");
        info.setProfitSharing(ProfitSharingEnum.N.toString());


        OrderInfoParent parent = new OrderInfoParent();
        parent.setIsRecharge("0");
        parent.setCreateTime(new Date());
        parent.setDiscountAmount(info.getDiscountAmount());
        parent.setDiscountRate(info.getDiscountRate());
        parent.setParentAmount(info.getOrderAmount());
        parent.setParentOrderNo(createParentOrderNo());
        parent.setPayAmount(info.getOrderAmount());
        parent.setPayByScore(info.getPayByScore());
        parent.setPayByBalance(info.getPayByBalance());
        //parent.setPayByScore(settle.getScore());
        parent.setFreightAmount(info.getFreightAmount());
        parent.setPayByRedBag(info.getPayByRedBag());
        parent.setPayMethod(PayMethodEnum.wechat.getKey());
        parent.setPayStatus(PayStatusEnum.unpaid.getKey());
        parent.setExpireDate(info.getExpireDate());
        parent.setUseCouponUid(info.getUseCouponUid());
        parent.setUseCouponAmount(info.getUseCouponAmount());
        parent.setProfitSharing(ProfitSharingEnum.N.toString());
        parent.setCustomerId(info.getCustomerUid());
        parent.setPlatformId(info.getPlatformUid());
        parent.setStoreId(info.getStoreId());
        if (!orderInfoParentService.save(parent)) {
            throw new BaseException("创建订单失败");
        }

        info.setParentOrderNo(parent.getParentOrderNo());
        boolean save = this.save(info);
        if (save) {
            /**
             * 查询客户等级,看是否有折扣这个权益,进行计算
             */
            CustomerPrivilege customerPrivilege = customerPrivilegeService.getByCustomerUid(customerInfo.getCustomerUid());
            BigDecimal discount = BigDecimal.ZERO;
            Long level = null;
            if (ObjectUtil.isNotEmpty(customerPrivilege)) {
                if (StringUtils.isEmpty(customerPrivilege.getPrivilegeValue())) {
                    customerPrivilege.setPrivilegeValue("0");
                }
                discount = new BigDecimal(Double.parseDouble(customerPrivilege.getPrivilegeValue())*0.1);
                level = customerPrivilege.getCustomeRgrade();
            }
            AtomicReference<Long> payAmount = new AtomicReference<>(0L);
            AtomicReference<Long> discountAmount = new AtomicReference<>(0L);
            BigDecimal finalDiscount = discount;
            Long finalLevel = level;
            vo.getList().forEach(itemVo -> {
                OrderInfoItem infoItem = new OrderInfoItem();
                infoItem.setOrderType(itemVo.getServiceType());
                infoItem.setOrderUid(info.getOrderUid());
                infoItem.setCreateUid(SecurityUtils.getUserId());
                infoItem.setCreateTime(DateUtil.date());
                infoItem.setDataStatus(DataStatus.valid.getKey());
                infoItem.setSaleStatus(DataStatus.invalid.getKey());
                infoItem.setItemNumber(itemVo.getItemNumber());
                infoItem.setDiscountAmount(0l);
                infoItem.setCustomerUid(info.getCustomerUid());
                infoItem.setStoreId(info.getStoreId());
                if (ReleaseShopTypeEnum.service.getKey().equals(itemVo.getServiceType())) {

                    /**
                     * 判断是否有sku id如果有 那么价格取sku的
                     *
                     */
                    if (ObjectUtil.isEmpty(itemVo.getSkuId())) {

                    } else {

                    }
                    infoItem.setPayAmount(infoItem.getItemAmount());


                } else {

                }

                payAmount.updateAndGet(v -> v + infoItem.getPayAmount());
                discountAmount.updateAndGet(v -> v + infoItem.getDiscountAmount());
                itemService.save(infoItem);
            });
            info.setPayAmount(payAmount.get());
            info.setDiscountAmount(discountAmount.get());
            this.updateById(info);
        }
        return info;
    }

    /**
     * 查询用户消费了多少
     *
     * @param customerUid
     * @return
     */
    @Override
    public String getOrderAmountByUid(Long customerUid) {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CUSTOMER_UID", customerUid);
        queryWrapper.eq("ORDER_STATUS", DataStatus.valid.getKey());
        queryWrapper.eq("PAY_STATUS", DataStatus.valid.getKey());
        queryWrapper.select("IFNULL(SUM(pay_Amount),0) pay_Amount");
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(orderInfo)) {
            return "0";
        }
        return MoneyUtils.changeF2B(orderInfo.getPayAmount());
    }

    /**
     * 查询订单详情
     *
     * @param orderUid 订单子ID
     * @return 订单子
     */
    @Override
    public OrderInfoVo selectOrderInfoById(Long orderUid) {
        OrderInfoVo vo = null;
        OrderInfo orderInfo = this.getById(orderUid);
        if (orderInfo != null) {
            if (SecurityUtils.getCustomerUid() != null) {
                if (orderInfo.getCustomerUid().longValue() != SecurityUtils.getCustomerUid()) {
                    throw new BaseException("您没有权限查看该订单详情");
                }
            }

            vo = new OrderInfoVo();
            BeanUtils.copyProperties(orderInfo, vo);

            if (PayStatusEnum.paid.getKey().equals(vo.getPayStatus()) && SendStatusEnum.unShip.getKey().equals(vo.getSendStatus())) {
                PlatformGeneralsettingsVo data = platformGeneralsettingsService.get(orderInfo.getPlatformUid());
                if (ObjectUtil.isNotEmpty(data)) {
                    Date expire = DateUtils.add(orderInfo.getPayTime(), Long.parseLong(data.getOrderPayment()));
                    if (System.currentTimeMillis() > expire.getTime())
                        vo.setShowCancelFlag(Boolean.TRUE);
                    else
                        vo.setShowCancelFlag(Boolean.FALSE);
                }
            }

            List<OrderItemVo> itemVoList = itemService.getByOrderUid(orderUid);
            if (itemVoList != null && itemVoList.size() > 0) {
                vo.setItemList(itemVoList);
            }


        }

        return vo;
    }

    private void addOrderTime(List<OrderTimeVo> timeVoList, OrderTimeVo timeVo, Integer status, Date time) {
        timeVo = new OrderTimeVo();
        timeVo.setStatus(status);
        timeVo.setTime(time);
        timeVo.setStatusName(OrderTimeStatusEnum.getNameByKey(status));
        timeVoList.add(timeVo);
    }

    /**
     * 新增订单子
     *
     * @param orderInfo 订单子
     * @return 结果
     */
    @Override
    public boolean insertOrderInfo(OrderInfo orderInfo) {

        return this.save(orderInfo);

    }

    @Override
    public boolean saveAdminOrderInfo(OrderInfo order) {
        OrderInfoParent parent = new OrderInfoParent();
        parent.setIsRecharge(OrderRechargeEnum.admin.getKey());
        parent.setOrderType("admin");
        parent.setCreateTime(new Date());
        parent.setDiscountAmount(0L);
        parent.setDiscountRate(0L);
        parent.setParentAmount(order.getPayAmount());
        parent.setParentOrderNo(createParentOrderNo());
        parent.setPayAmount(order.getPayAmount());
        parent.setPayByScore(order.getPayByScore());
        parent.setPayByBalance(0L);
        parent.setFreightAmount(0L);
        parent.setPayByRedBag(0L);
        parent.setPayMethod("wechat");
        parent.setPayStatus(PayStatusEnum.unpaid.getKey());
        parent.setProfitSharing(ProfitSharingEnum.Y.toString());
        parent.setPlatformId(SecurityUtils.getCustomerPlatformUid());
        Long score = 0L;
        if (orderInfoParentService.save(parent)) {

            /**
             * 保存订单信息
             */
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setAutoReceiveTime(null);
            orderInfo.setCancelTime(null);
            orderInfo.setCommentStatus(CommentStatusEnum.unComment.getKey());
            orderInfo.setCreateTime(parent.getCreateTime());
            orderInfo.setCurrencyUnit("RMB");
            orderInfo.setCustomerName(order.getCustomerName());
            orderInfo.setPhone(order.getPhone());
            orderInfo.setOrderTitle(order.getOrderTitle());
            orderInfo.setDiscountRate(parent.getDiscountRate());
            orderInfo.setExpireDate(parent.getExpireDate());
            orderInfo.setInvoiceStatus(InvoiceStatusEnum.unInvoice.getKey());
            orderInfo.setIp(SecurityUtils.getCustomerClientIp());
            orderInfo.setOrderAmount(order.getPayAmount());
            orderInfo.setOrderNo(createOrderNo());
            orderInfo.setOrderPackStatus(PackStatusEnum.collect.getKey());
            orderInfo.setOrderStatus(OrderStatusEnum.effect.getKey());
            orderInfo.setOrderType(order.getOrderType());
            orderInfo.setPayAmount(0L);
            orderInfo.setPayByBalance(0L);
            orderInfo.setPayMethod("wechat");
            orderInfo.setPayByRedBag(0L);
            orderInfo.setPayStatus(PayStatusEnum.unpaid.getKey());
            orderInfo.setParentOrderNo(parent.getParentOrderNo());
            orderInfo.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
            orderInfo.setPlatSource(PlatSourceEnum.manager.getKey());
            orderInfo.setSendStatus(SendStatusEnum.unShip.getKey());
            orderInfo.setUseCouponAmount(0L);
            orderInfo.setPayByScore(score);
            orderInfo.setUseCouponUid(parent.getUseCouponUid());
            orderInfo.setUpdateTime(parent.getCreateTime());
            orderInfo.setUpdateUser(SecurityUtils.getUserId());
            orderInfo.setUpdateUserName(SecurityUtils.getUsername());
            orderInfo.setCreateName(SecurityUtils.getUsername());
            orderInfo.setCreateUid(SecurityUtils.getUserId());
            orderInfo.setCreateTime(parent.getCreateTime());
            if (this.save(orderInfo)) {
                return true;
            }
        }
        return false;
    }

    private Double toDouble(Long price){
        if (price != null)
            return price/100.0;
        else
            return 0.0;
    }

    @Override
    public TableDataInfo exportOrderDataInfo(OrderInfo orderInfo){
        List<OrderInfo> list = queryList(orderInfo);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        rspData.setTotal(new PageInfo(list).getTotal());
        List<OrderExport> exports = new ArrayList<>();
        for(OrderInfo oi:list){
            List<OrderItemVo> items = oi.getItemList();
            int j=0;
            for (OrderItemVo i:items){
                OrderExport export = new OrderExport();
                BeanUtils.copyProperties(oi,export);

                exports.add(export);
                j++;
            }
        }
        rspData.setRows(exports);
        return rspData;
    }

    @Override
    public List<OrderExport> exportList(OrderInfo orderInfo){
        List<OrderInfo> list = queryList(orderInfo);
        List<OrderExport> exports = new ArrayList<>();
        for(OrderInfo oi:list){
            List<OrderItemVo> items = oi.getItemList();
            if (items == null || items.size()==0) continue;
            for (OrderItemVo i:items){
                OrderExport export = new OrderExport();
                BeanUtils.copyProperties(oi,export);
                export.setProName(i.getProName());
                export.setSkuDesc(i.getSkuDesc());
                export.setScore(i.getPayByScore());
                export.setMoney(toDouble(i.getPayAmount()));
                export.setCostPrice(i.getCostPrice());
                export.setPayStatus("未支付");
                if ("1".equals(i.getPayStatus())) {
                    export.setPayStatus("已支付");
                }
                if (export.getOrderType().equalsIgnoreCase("good")){
                    export.setOrderType("下载");
                }else if (export.getOrderType().equalsIgnoreCase("maiduan")){
                    export.setOrderType("买断");
                }
                export.setPayDate(i.getPayDate());
                export.setPlatSource(oi.getPlatSourceName());
                exports.add(export);

            }
        }
        return exports;
    }

    /**
     * 查询订单子列表
     *
     * @param orderInfo 订单子
     * @return 订单子
     */
    @Override
    public List<OrderInfo> queryList(OrderInfo orderInfo) {
        if (StringUtils.isNotEmpty(orderInfo.getPayMethod())){
            List<String> list = new ArrayList<>();
            String[] pays = orderInfo.getPayMethod().split(",");
            for (String p:pays) {
                list.add(p);
            }
            orderInfo.setPayMethodList(list);
        }
        QueryWrapper<OrderInfo> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getOrderUid())) && orderInfo.getOrderUid() != null) {
            queryWrapper.eq("ORDER_UID", orderInfo.getOrderUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getSupplierUid())) && orderInfo.getSupplierUid() != null) {
            queryWrapper.eq("SUPPLIER_UID", orderInfo.getSupplierUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getOrderTitle())) && orderInfo.getOrderTitle() != null) {
            queryWrapper.like("ORDER_TITLE", orderInfo.getOrderTitle());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getOrderType())) && orderInfo.getOrderType() != null) {
            queryWrapper.eq("ORDER_TYPE", orderInfo.getOrderType());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getOrderNo())) && orderInfo.getOrderNo() != null) {
            queryWrapper.like("ORDER_NO", orderInfo.getOrderNo());
        }
        if (StringUtils.isNotEmpty(orderInfo.getSupplierName())) {
            queryWrapper.like("Supplier_Name", orderInfo.getSupplierName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getParentOrderNo())) && orderInfo.getParentOrderNo() != null) {
            queryWrapper.eq("PARENT_ORDER_NO", orderInfo.getParentOrderNo());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getCustomerUid())) && orderInfo.getCustomerUid() != null) {
            queryWrapper.eq("CUSTOMER_UID", orderInfo.getCustomerUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getCustomerName())) && orderInfo.getCustomerName() != null) {
            queryWrapper.like("CUSTOMER_NAME", orderInfo.getCustomerName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getPhone())) && orderInfo.getPhone() != null) {
            queryWrapper.like("PHONE", orderInfo.getPhone());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getOrderStatus())) && orderInfo.getOrderStatus() != null) {
            queryWrapper.eq("ORDER_STATUS", orderInfo.getOrderStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getPayStatus())) && orderInfo.getPayStatus() != null) {
            queryWrapper.eq("PAY_STATUS", orderInfo.getPayStatus());
        }
        /*
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getPayMethod())) && orderInfo.getPayMethod() != null) {
            queryWrapper.eq("PAY_METHOD", orderInfo.getPayMethod());
        }*/
        if (orderInfo.getPayMethodList() != null){
            queryWrapper.in("PAY_METHOD", orderInfo.getPayMethodList());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getPlatSource())) && orderInfo.getPlatSource() != null) {
            queryWrapper.eq("PLAT_SOURCE", orderInfo.getPlatSource());
        }
        if (orderInfo.getPayTimeArray() != null && orderInfo.getPayTimeArray().size() > 0) {
            queryWrapper.ge("PAY_TIME", orderInfo.getPayTimeArray().get(0));
            if (orderInfo.getPayTimeArray().size() > 1)
                queryWrapper.le("PAY_TIME", orderInfo.getPayTimeArray().get(1) + " 23:59:59");
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getCancelTime())) && orderInfo.getCancelTime() != null) {
            queryWrapper.eq("CANCEL_TIME", orderInfo.getCancelTime());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getExpireDate())) && orderInfo.getExpireDate() != null) {
            queryWrapper.eq("EXPIRE_DATE", orderInfo.getExpireDate());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getInvoiceUid())) && orderInfo.getInvoiceUid() != null) {
            queryWrapper.eq("INVOICE_UID", orderInfo.getInvoiceUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getInvoiceStatus())) && orderInfo.getInvoiceStatus() != null) {
            queryWrapper.eq("INVOICE_STATUS", orderInfo.getInvoiceStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getDeliverMethod())) && orderInfo.getDeliverMethod() != null) {
            queryWrapper.eq("DELIVER_METHOD", orderInfo.getDeliverMethod());
        }
        if (orderInfo.getSendTimeArray() != null && orderInfo.getSendTimeArray().size() > 0) {
            queryWrapper.ge("SEND_TIME", orderInfo.getSendTimeArray().get(0));
            if (orderInfo.getSendTimeArray().size() > 1)
                queryWrapper.le("SEND_TIME", orderInfo.getSendTimeArray().get(1) + " 23:59:59");
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getSendStatus())) && orderInfo.getSendStatus() != null) {
            queryWrapper.eq("SEND_STATUS", orderInfo.getSendStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getOrderPackStatus())) && orderInfo.getOrderPackStatus() != null) {
            queryWrapper.eq("ORDER_PACK_STATUS", orderInfo.getOrderPackStatus());
        }
        if (orderInfo.getSignTimeArray() != null && orderInfo.getSignTimeArray().size() > 0) {
            queryWrapper.ge("SIGN_TIME", orderInfo.getSignTimeArray().get(0));
            if (orderInfo.getSignTimeArray().size() > 1)
                queryWrapper.le("SIGN_TIME", orderInfo.getSignTimeArray().get(1) + " 23:59:59");
        }
        if (orderInfo.getReceiveTimeArray() != null && orderInfo.getReceiveTimeArray().size() > 0) {
            queryWrapper.ge("RECEIVE_TIME", orderInfo.getReceiveTimeArray().get(0));
            if (orderInfo.getReceiveTimeArray().size() > 1)
                queryWrapper.le("RECEIVE_TIME", orderInfo.getReceiveTimeArray().get(1) + " 23:59:59");
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getCommentStatus())) && orderInfo.getCommentStatus() != null) {
            queryWrapper.eq("COMMENT_STATUS", orderInfo.getCommentStatus());
        }
        if (orderInfo.getCommentTimeArray() != null && orderInfo.getCommentTimeArray().size() > 0) {
            queryWrapper.ge("COMMENT_TIME", orderInfo.getCommentTimeArray().get(0));
            if (orderInfo.getCommentTimeArray().size() > 1)
                queryWrapper.le("COMMENT_TIME", orderInfo.getCommentTimeArray().get(1) + " 23:59:59");
        }
        if (orderInfo.getCreateTimeArray() != null && orderInfo.getCreateTimeArray().size() > 0) {
            queryWrapper.ge("CREATE_TIME", orderInfo.getCreateTimeArray().get(0));
            if (orderInfo.getCreateTimeArray().size() > 1)
                queryWrapper.le("CREATE_TIME", orderInfo.getCreateTimeArray().get(1) + " 23:59:59");
        }

        if (ObjectUtil.isNotEmpty(orderInfo.getProName()) || ObjectUtil.isNotEmpty(orderInfo.getProNo())) {
            String subSql = " and ORDER_UID  in (select ORDER_UID from order_info_item where DATA_STATUS = 1 ";
            if (ObjectUtil.isNotEmpty(orderInfo.getProName())){
                subSql += " and PRO_NAME like '%" + orderInfo.getProName() + "%'";
            }
            if (ObjectUtil.isNotEmpty(orderInfo.getProNo())){
                subSql += " and PRO_NO like '%" + orderInfo.getProNo() + "%'";
            }
            subSql += ")  order by create_time desc ";
            queryWrapper.last(subSql);
        } else {
            queryWrapper.orderByDesc("CREATE_TIME");
        }

        List<OrderInfo> list = orderInfoMapper.selectList(queryWrapper);

        if (ObjectUtil.isNotEmpty(list)) {

            List<OrderItemVo> itemVoList = null;

            for (OrderInfo order : list) {

                itemVoList = itemService.getByOrderUid(order.getOrderUid());
                if (itemVoList != null && itemVoList.size() > 0) {
                    order.setItemList(itemVoList);
                }
            }
        }

        return list;
    }


    /**
     * 查询订单子列表
     *
     * @param orderInfo 订单子
     * @return 订单子
     */
    @Override
    public OrderInfo sumQueryList(OrderInfo orderInfo) {
        QueryWrapper<OrderInfo> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(orderInfo.getPayMethod())){
            List<String> list = new ArrayList<>();
            String[] pays = orderInfo.getPayMethod().split(",");
            for (String p:pays) {
                list.add(p);
            }
            orderInfo.setPayMethodList(list);
        }
        queryWrapper.select("sum(pay_amount) as pay_amount");
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getOrderUid())) && orderInfo.getOrderUid() != null) {
            queryWrapper.eq("ORDER_UID", orderInfo.getOrderUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getSupplierUid())) && orderInfo.getSupplierUid() != null) {
            queryWrapper.eq("SUPPLIER_UID", orderInfo.getSupplierUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getSupplierName())) && orderInfo.getSupplierName() != null) {
            queryWrapper.like("SUPPLIER_NAME", orderInfo.getSupplierName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getOrderType())) && orderInfo.getOrderType() != null) {
            queryWrapper.eq("ORDER_TYPE", orderInfo.getOrderType());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getOrderNo())) && orderInfo.getOrderNo() != null) {
            queryWrapper.like("ORDER_NO", orderInfo.getOrderNo());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getParentOrderNo())) && orderInfo.getParentOrderNo() != null) {
            queryWrapper.eq("PARENT_ORDER_NO", orderInfo.getParentOrderNo());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getCustomerUid())) && orderInfo.getCustomerUid() != null) {
            queryWrapper.eq("CUSTOMER_UID", orderInfo.getCustomerUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getCustomerName())) && orderInfo.getCustomerName() != null) {
            queryWrapper.like("CUSTOMER_NAME", orderInfo.getCustomerName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getPhone())) && orderInfo.getPhone() != null) {
            queryWrapper.like("PHONE", orderInfo.getPhone());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getOrderStatus())) && orderInfo.getOrderStatus() != null) {
            queryWrapper.eq("ORDER_STATUS", orderInfo.getOrderStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getPayStatus())) && orderInfo.getPayStatus() != null) {
            queryWrapper.eq("PAY_STATUS", orderInfo.getPayStatus());
        }
        /*
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getPayMethod())) && orderInfo.getPayMethod() != null) {
            queryWrapper.eq("PAY_METHOD", orderInfo.getPayMethod());
        }*/
        if (orderInfo.getPayMethodList() != null){
            queryWrapper.in("PAY_METHOD", orderInfo.getPayMethodList());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getPlatSource())) && orderInfo.getPlatSource() != null) {
            queryWrapper.eq("PLAT_SOURCE", orderInfo.getPlatSource());
        }
        if (orderInfo.getPayTimeArray() != null && orderInfo.getPayTimeArray().size() > 0) {
            queryWrapper.ge("PAY_TIME", orderInfo.getPayTimeArray().get(0));
            if (orderInfo.getPayTimeArray().size() > 1)
                queryWrapper.le("PAY_TIME", orderInfo.getPayTimeArray().get(1) + " 23:59:59");
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getCancelTime())) && orderInfo.getCancelTime() != null) {
            queryWrapper.eq("CANCEL_TIME", orderInfo.getCancelTime());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getExpireDate())) && orderInfo.getExpireDate() != null) {
            queryWrapper.eq("EXPIRE_DATE", orderInfo.getExpireDate());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getInvoiceUid())) && orderInfo.getInvoiceUid() != null) {
            queryWrapper.eq("INVOICE_UID", orderInfo.getInvoiceUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getInvoiceStatus())) && orderInfo.getInvoiceStatus() != null) {
            queryWrapper.eq("INVOICE_STATUS", orderInfo.getInvoiceStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getDeliverMethod())) && orderInfo.getDeliverMethod() != null) {
            queryWrapper.eq("DELIVER_METHOD", orderInfo.getDeliverMethod());
        }
        if (orderInfo.getSendTimeArray() != null && orderInfo.getSendTimeArray().size() > 0) {
            queryWrapper.ge("SEND_TIME", orderInfo.getSendTimeArray().get(0));
            if (orderInfo.getSendTimeArray().size() > 1)
                queryWrapper.le("SEND_TIME", orderInfo.getSendTimeArray().get(1) + " 23:59:59");
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getSendStatus())) && orderInfo.getSendStatus() != null) {
            queryWrapper.eq("SEND_STATUS", orderInfo.getSendStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getOrderPackStatus())) && orderInfo.getOrderPackStatus() != null) {
            queryWrapper.eq("ORDER_PACK_STATUS", orderInfo.getOrderPackStatus());
        }
        if (orderInfo.getSignTimeArray() != null && orderInfo.getSignTimeArray().size() > 0) {
            queryWrapper.ge("SIGN_TIME", orderInfo.getSignTimeArray().get(0));
            if (orderInfo.getSignTimeArray().size() > 1)
                queryWrapper.le("SIGN_TIME", orderInfo.getSignTimeArray().get(1) + " 23:59:59");
        }
        if (orderInfo.getReceiveTimeArray() != null && orderInfo.getReceiveTimeArray().size() > 0) {
            queryWrapper.ge("RECEIVE_TIME", orderInfo.getReceiveTimeArray().get(0));
            if (orderInfo.getReceiveTimeArray().size() > 1)
                queryWrapper.le("RECEIVE_TIME", orderInfo.getReceiveTimeArray().get(1) + " 23:59:59");
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getCommentStatus())) && orderInfo.getCommentStatus() != null) {
            queryWrapper.eq("COMMENT_STATUS", orderInfo.getCommentStatus());
        }
        if (orderInfo.getCommentTimeArray() != null && orderInfo.getCommentTimeArray().size() > 0) {
            queryWrapper.ge("COMMENT_TIME", orderInfo.getCommentTimeArray().get(0));
            if (orderInfo.getCommentTimeArray().size() > 1)
                queryWrapper.le("COMMENT_TIME", orderInfo.getCommentTimeArray().get(1) + " 23:59:59");
        }
        if (orderInfo.getCreateTimeArray() != null && orderInfo.getCreateTimeArray().size() > 0) {
            queryWrapper.ge("CREATE_TIME", orderInfo.getCreateTimeArray().get(0));
            if (orderInfo.getCreateTimeArray().size() > 1)
                queryWrapper.le("CREATE_TIME", orderInfo.getCreateTimeArray().get(1) + " 23:59:59");
        }
        /*
        if (ObjectUtil.isNotEmpty(orderInfo.getStoreId())) {
            queryWrapper.eq("store_id", orderInfo.getStoreId());
        }*/
        if (orderInfo.getStoreIds() != null && orderInfo.getStoreIds().size()>0){
            queryWrapper.in("store_id",orderInfo.getStoreIds());
        }


//        Long platFormUid = SecurityUtils.getPlatformId();
//        if (platFormUid != null && platFormUid > 0)
//            queryWrapper.eq("PLATFORM_UID", platFormUid);
//        else
//            throw new BaseException("账号异常");

        Long supplierId = SecurityUtils.getSupplierId();
        if (supplierId != null && supplierId > 0)
            queryWrapper.eq("SUPPLIER_UID", supplierId);
        if (ObjectUtil.isNotEmpty(orderInfo.getProName())) {
            queryWrapper.last("  and ORDER_UID  in (select ORDER_UID from order_info_item where DATA_STATUS = 1  " +
                    "  and PRO_NAME like '%" + orderInfo.getProName() + "%')  ");
        }

        OrderInfo rst = orderInfoMapper.selectOne(queryWrapper);
        return rst;
    }

    /**
     * 自提发货
     * @param orderInfo
     * @return
     */
    @Override
    public boolean ziTiOrderInfo(OrderInfo orderInfo){
        OrderInfo info = this.getById(orderInfo.getOrderUid());
        if(ObjectUtil.isEmpty(info)){
            throw new BaseException("订单不存在");
        }
        Date now = new Date();

        OrderInfo order = new OrderInfo();
        order.setSendStatus(SendStatusEnum.ship.getKey());
        order.setSendTime(now);
        order.setAutoReceiveTime(now);
        order.setUpdateTime(now);
        order.setUpdateUser(SecurityUtils.getUserId());
        order.setUpdateUserName(SecurityUtils.getUsername());
        order.setOrderUid(orderInfo.getOrderUid());
     return    this.updateById(order);
    }

    /**
     * 发货
     *
     * @param orderInfo 订单子
     * @return 结果
     */
    @Override
    public boolean updateOrderInfo(OrderInfo orderInfo) {
        if (ObjectUtil.isEmpty(orderInfo.getDeliverType()))
            throw new BaseException("缺少发货类型参数");
        if (ObjectUtil.isEmpty(orderInfo.getKdUid()))
            throw new BaseException("缺少快递公司参数");
        if (ObjectUtil.isEmpty(orderInfo.getExpressNo()))
            throw new BaseException("缺少快递单号参数");
        if (ObjectUtil.isEmpty(orderInfo.getOrderUid()))
            throw new BaseException("缺少订单ID参数");
        if (ObjectUtil.isEmpty(orderInfo.getAddressUid()))
            throw new BaseException("缺少用户收货地址信息");

        OrderInfo order = this.getById(orderInfo.getOrderUid());
        if (ObjectUtil.isNull(order))
            throw new BaseException("没有找到订单信息");

        Date now = new Date();

        Long time = 0L;
        OrderShipAutoVo shipAuto = shipAutoService.getShipAuto(order.getPlatformUid());
        if (ObjectUtil.isNull(shipAuto))
            throw new BaseException("没有找到自动收货配置信息");
        time = shipAuto.getAutoDate();

        if (time == null) time = 7L;

        order.setSendStatus(SendStatusEnum.ship.getKey());
        order.setSendTime(now);
        order.setAutoReceiveTime(DateUtils.addDay(now, time.intValue()));



        CustomerAddressVo addressVo = iCustomerAddressService.getCustomerAddressInfo(orderInfo.getAddressUid());
        if (addressVo == null) throw new BaseException("没有找到用户收货地址信息");
        OrderShipDeliver deliver = new OrderShipDeliver();
        deliver.setPlatformUid(order.getPlatformUid());
        deliver.setOrderUid(order.getOrderUid());
        deliver.setOrderNo(order.getOrderNo());
        deliver.setDeliverType(orderInfo.getDeliverType());
        deliver.setCustomerUid(order.getCustomerUid());
        deliver.setCustomerName(order.getCustomerName());

        deliver.setDeliverAmount(order.getFreightAmount().toString());
        if (ObjectUtil.isNotEmpty(orderInfo.getFreightAmount()))
            deliver.setDeliverAmount(orderInfo.getFreightAmount().toString());

        deliver.setDeliverMethod(order.getDeliverMethod());

        deliver.setExpressNo(orderInfo.getExpressNo());
        deliver.setPackStatus(PackStatusEnum.collect.getKey());
        deliver.setAddressUid(order.getAddressUid());
        deliver.setProvince(addressVo.getProvinceName());
        deliver.setCity(addressVo.getCityName());
        deliver.setCounty(addressVo.getCountyName());
        deliver.setAddressDetail(addressVo.getAddress());
        deliver.setConsigneeName(addressVo.getName());
        deliver.setMobileNum(addressVo.getMobile());
        deliver.setZipCode(String.valueOf(addressVo.getPostCode()));

        deliverService.save(deliver);

        //发货通知==========================
        if (DeliverTypeEnum.normal.getKey().equals(orderInfo.getDeliverType())) {

            String page = "";
            String openId = "";
            String proName = "";
            //MessageEntity entity = null;
            WechatInfomation infomation = null;
            WeChatInfomationOrder infomationOrder = null;

            page = "pages/orderDetail/orderDetail?orderUid=" + order.getOrderUid();

            List<OrderItemVo> list = itemService.getByOrderUid(order.getOrderUid());
            if (ObjectUtil.isNotEmpty(list))
                proName = list.get(0).getProName();

            CustomerVo customerVo = iCustomerInfoService.getCustomerVo(order.getCustomerUid());
            if (ObjectUtil.isNotEmpty(customerVo)) {
                openId = customerVo.getOpenID();
            } else
                throw new BaseException("缺少用户openId参数！");

            infomationOrder = new WeChatInfomationOrder();
            infomationOrder.setProName(proName);
            infomationOrder.setOrderNo(order.getOrderNo());
            infomationOrder.setOrderMoney(order.getPayAmountStr());
            infomationOrder.setExpressNo(orderInfo.getExpressNo());
            //infomationOrder.setExpressCompany(mp.getKdCompany());
            infomationOrder.setDeliverTime(DateUtil.formatDateTime(now));

            infomation = new WechatInfomation();
            infomation.setPage(page);
            infomation.setTouser(openId);
            infomation.setData(infomationOrder);
            infomation.setInfomationType(WechatInfomationEnum.shipmentsOrder.getValue());


        }

        return this.updateById(order);
    }

    /**
     * 批量删除订单子
     *
     * @param orderUids 需要删除的订单子ID
     * @return 结果
     */
    @Override
    public boolean deleteOrderInfoByIds(Long[] orderUids) {
        return this.removeByIds(Arrays.asList(orderUids));
    }


    /**
     * 查询未结算的订单
     *
     * @param itemApi
     * @return
     */
    @Override
    public List<com.probox.order.api.domain.OrderSettlementVo> getBySettlement(ItemSettlementVo itemApi) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
        return orderInfoMapper.selectOrderById(itemApi);
    }

    @Override
    public List<com.probox.order.api.domain.OrderSettlementVo> getOrderById(Long[] itemUids) {
//        orderInfoMapper.selectOrderByIds(itemUids);
//        if(itemUids!=null && itemUids.length>0){
//            QueryWrapper<OrderInfoItem> orderInfoItemQueryWrapper = new QueryWrapper<>();
//            orderInfoItemQueryWrapper.in("ITEM_UID",itemUids);
//            orderInfoItemQueryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
//            List<OrderInfoItem> list = orderInfoItemMapper.selectList(orderInfoItemQueryWrapper.select("ITEM_UID", "SUPPLIER_UID", "ORDER_UID", "ACTIVITY_PRO_UID", "PRO_UID", "PRO_NAME", "SKU_UID", "SKU_DESC", "IMG_URL", "COST_PRICE", "ITEM_NUMBER", "ITEM_AMOUNT", "SETTLEMENT_STATUS", "SALE_STATUS"));
//            List<OrderSettlementVo> collect = list.stream().map(o -> {
//                OrderSettlementVo orderInfoItemApi = new OrderSettlementVo();
//                BeanUtils.copyProperties(o, orderInfoItemApi);
//                return orderInfoItemApi;
//            }).collect(Collectors.toList());
//            return collect;
//        }
//        throw new Error("订单不存在");

        return orderInfoMapper.selectOrderByIds(itemUids);
    }


    // -------------------------------------前端订单接口处理--------------------------------------

    /**
     * 合计购物车金额
     *
     * @param settle
     */
    private void tatolSettlement(OrderSettlementVo settle) {
        List<OrderShopCart> list = settle.getCarts();
        //商品总额
        Long amount = 0L;
        //非活动商品总额
        Long normalShopAmount = 0L;
        //总积分
        Long score = 0L;

        //会员折扣
        Long disCount = 0L;
        int i = 0;
        for (OrderShopCart cart : list) {
            amount += cart.getCartAmount();
            if (cart.getActivityUid() == null) {
                normalShopAmount += cart.getCartAmount();
            }
            if (cart.isUseMemberDiscount()) {
                if (cart.getDiscountMemberLevel().intValue() <= settle.getMemberGrade() && settle.getDiscountRate()>0) {
                    disCount += cart.getCartAmount() * (100 - settle.getDiscountRate()) / 100;
                }
            }
            if (cart.getScore() != null)
                score += cart.getTotalScore();

            if (cart.isUseBoluoGoldCoin()) {
                settle.setCanUseGoldCionAmount(cart.getCartAmount() + settle.getCanUseGoldCionAmount());
            }
            if (cart.isUseBoluosilverCoin()) {
                settle.setCanUseSilverCionAmount(cart.getCartAmount() + settle.getCanUseSilverCionAmount());
            }
            if (cart.isUseCoupon()) {
                settle.setCanUseCouponAmount(cart.getCartAmount() + settle.getCanUseCouponAmount());
            }

            //新人免费领控制，至少和一个或以上非免费商品一同下单
            if (ActivityTypeEnum.free.getKey().equals(cart.getActivityType()))
                i++;
            if (i > 1 || (i == 1 && list.size() == 1))
                throw new BaseException("免费领的商品不能单独购买！");
        }
        settle.setNormalShopAmount(normalShopAmount);
        settle.setShopAmount(amount);
        settle.setScoreAmount(score);
        settle.setDiscountAmount(disCount);
        logger.info("\n==========合计购物车金额，商品总额：{}，非活动商品总额：{}，结算总积分：{}=========",
                settle.getShopAmount(), settle.getNormalShopAmount(), settle.getScoreAmount());
    }

    /**
     * 预下单接口
     *
     * @param settle
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> preCreateOrder(OrderSettlementVo settle) throws Exception {
        logger.info("\n==========预下单接口参数：{}=========", JSON.toJSONString(settle));
        Map<String, Object> rst = new HashMap<>();
        //设置身份
        settle.setCustomerId(SecurityUtils.getCustomerUid());
        settle.setPlatformId(SecurityUtils.getCustomerPlatformUid());
        if (settle.getCouponId() != null){
            settle.setRedBag(0L);
        }
        /**
         * 验证结算商品状态
         */
        ShopCartVo shopCart = new ShopCartVo();
        shopCart.setCartList(settle.getCartList());
        shopCart.setStoreId(settle.getStoreId());
        List<OrderShopCart> carts = shopCartService.list(shopCart);
        if (carts.size() != settle.getCartList().size()) {
            throw new BaseException("部分商品已结算或移除，请重新选择再结算");
        }
        logger.info("\n=======预结算购物车信息：{}==========\n", JSON.toJSONString(carts));

        settle.setCarts(carts);


        //验证用户资料，折扣金额
        getUserInfo(settle);

        //计算结算总额，积分
        tatolSettlement(settle);
        if (settle.getCanUseGoldCionAmount() == 0L) {
            settle.setBalance(0L);
        }
        if (settle.getCanUseSilverCionAmount() == 0L) {
            settle.setRedBag(0L);
        }
        if (settle.getCanUseCouponAmount() == 0L) {
            settle.setCouponId(null);
        }
        //验证优惠券资料
        checkCoupon(settle);
        //验证客户地址信息
        if (settle.getAddressId() != null) {
            CustomerAddressVo addressVo = checkAddress(settle);
            //会员没有包邮特权，需要计算邮费
            if (!settle.getFreeFreight()) {
                checkFreight(settle, addressVo, settle.getShopAmount());
            }
        } else {
            settle.setFreight(0L);
        }
        //检验余额，积分或红包是否足够
        CustomerFundVo customerFund = checkBalanceAndRedBagAndScore(settle);

        //商品总额
        Long shopAmount = settle.getShopAmount();
        //物流费用
        Long fregiht = settle.getFreight();
        //折扣
        Long discount = settle.getDiscountAmount();
        if (discount == null) {
            discount = 0L;
        }

        //优惠金额
        Long coupon = settle.getCouponAmount();
        if (coupon == null) {
            coupon = 0L;
        }

        //积分
        Long score = settle.getScoreAmount();
        if (score == null) {
            score = 0L;
        }
        //红包
        Long redBag = settle.getRedBag();
        if (redBag == null) {
            redBag = 0L;
        }
        //余额
        Long balance = settle.getBalance();
        if (balance == null) {
            balance = 0L;
        }

        rst.put("shopAmount", MoneyUtils.changeF2Y(shopAmount));
        if (fregiht > 0) {
            rst.put("freight", MoneyUtils.changeF2Y(fregiht));
        } else {
            rst.put("freight", "包邮");
        }
        if (discount > 0) {
            rst.put("discount", MoneyUtils.changeF2Y(discount));
        }


        if (coupon > 0) {
            rst.put("coupon", MoneyUtils.changeF2Y(coupon));
        }
        if (score > 0) {
            rst.put("score", score);
        }

        //付款金额
        Long payAmount = shopAmount + fregiht;
        rst.put("totalAmount", MoneyUtils.changeF2Y(payAmount));
        //优先使用银币抵扣
        if (redBag > 0) {
            if (redBag + discount + coupon - payAmount > 0) {
                redBag = payAmount - coupon - discount;
                rst.put("redBag", MoneyUtils.changeF2Y(redBag));
                balance = 0L;
                payAmount = 0L;
            } else {
                rst.put("redBag", MoneyUtils.changeF2Y(redBag));
                //payAmount = shopAmount + fregiht - discount - coupon - redBag;
            }
        }
        if (payAmount > 0) {
            payAmount = payAmount - discount - coupon - redBag - balance;
            if (payAmount < 0) {
                if (balance > 0) {
                    balance = balance + payAmount;
                }
                payAmount = 0L;
            }
        }

        if (balance > 0) {
            rst.put("balance", MoneyUtils.changeF2Y(balance));
        }
        rst.put("payAmount", MoneyUtils.changeF2Y(payAmount));

        if (settle.getNormalShopAmount() > 0 && settle.getCanUseCouponAmount() > 0) {
            rst.put("useCoupon", "1");
        } else {
            rst.put("useCoupon", "0");
        }

        if (customerFund.getRedBag() > 0 && settle.getCanUseSilverCionAmount() > 0 && coupon<=0) {
            rst.put("useRedBag", "1");
        } else {
            rst.put("useRedBag", "0");
        }

        if (customerFund.getBalance() > 0 && payAmount > 0 && settle.getCanUseGoldCionAmount() > 0) {
            rst.put("useBalance", "1");
        } else {
            if (balance == 0) {
                rst.put("useBalance", "0");
            } else {
                rst.put("useBalance", "1");
            }
        }

        if (settle.getScoreAmount() > 0) {
            rst.put("useScore", "1");
        } else {
            rst.put("useScore", "0");
        }

        return rst;
    }

    private void resetUseCoupon(OrderInfoItem cart,String proType,CouponInfoDetailVo copuon){
        if (cart.isUseCoupon() && copuon != null && StringUtils.isNotEmpty(copuon.getCouponProType()) && copuon.getCouponProType().equals(proType)){
            if (StringUtils.isNotEmpty(copuon.getCouponProUids())){
                String[] proIds = copuon.getCouponProUids().split(",");
                boolean find = false;
                for(String id:proIds){
                    if (id.equals(String.valueOf(cart.getProUid()))){
                        find = true;
                        break;
                    }
                }
                if (!find){
                    cart.setUseCoupon(find);
                }
            }
        }
    }

    private void resetUseCoupon(OrderShopCart cart,String proType,CouponInfoDetailVo copuon){
        if (cart.isUseCoupon() && copuon != null && StringUtils.isNotEmpty(copuon.getCouponProType()) && copuon.getCouponProType().equals(proType)){
            if (StringUtils.isNotEmpty(copuon.getCouponProUids())){
                String[] proIds = copuon.getCouponProUids().split(",");
                boolean find = false;
                for(String id:proIds){
                    if (id.equals(String.valueOf(cart.getProUid()))){
                        find = true;
                        break;
                    }
                }
                if (!find){
                    cart.setUseCoupon(find);
                }
            }
        }
    }

    @Override
    public Map<String, Object> preEditOrder(OrderSettlementVo settle) throws Exception {
        logger.info("\n==========预下单接口参数：{}=========", JSON.toJSONString(settle));
        Map<String, Object> rst = new HashMap<>();
        //设置身份
        settle.setCustomerId(SecurityUtils.getCustomerUid());
        settle.setPlatformId(SecurityUtils.getCustomerPlatformUid());
        if (settle.getCouponId() != null){
            settle.setRedBag(0L);
        }
        OrderInfo orderInfo = this.getById(settle.getOrderId());
        if (orderInfo == null || !orderInfo.getOrderStatus().equals(DataStatus.valid.getKey()) || orderInfo.getCustomerUid().longValue() != settle.getCustomerId()) {
            throw new BaseException("没有找到订单信息");
        }
        if (orderInfo.getPayStatus().equals(DataStatus.valid.getKey())) {
            throw new BaseException("该订单已支付");
        }

        List<OrderInfoItem> itemVoList = itemService.selectByOrderId(orderInfo.getOrderUid());
        if (itemVoList == null || itemVoList.size() == 0) {
            throw new BaseException("该订单没有需要结算的商品");
        }

        //检验余额，积分或红包是否足够
        CustomerFundVo customerFund = null;
        CustomerFund fund = iCustomerFundService.getByCustomerId(orderInfo.getCustomerUid());
        if (ObjectUtil.isEmpty(fund)) {
            throw new BaseException("没有找到会员钱包信息");
        }
        customerFund = new CustomerFundVo();
        BeanUtils.copyProperties(fund, customerFund);
        logger.info("\n==========查询用户资金信息parameter:{}==========\n===========result:{}===========\n",
                settle.getCustomerId(), JSONObject.toJSONString(customerFund));

        if (orderInfo.getIsDdl().equals(DataStatus.valid.getKey())){

        }else{
            for (OrderInfoItem cart : itemVoList) {
                if (cart.getOrderType().equals(CardServiceTypeEnum.product.getKey())) {
                    ProductInfoVo p = iProductInfoService.getProductDetail(cart.getProUid());
                    if (p != null) {
                        if (!DataStatus.valid.getKey().equals(p.getDataStatus())) {
                            throw new BaseException("商品未上架，不能结算");
                        }
                        if (!DataStatus.valid.getKey().equals(p.getAuditStatus())) {
                            throw new BaseException("商品未上架，不能结算");
                        }
                        cart.setUseBoluoGoldCoin(DataStatus.valid.getKey().equals(p.getIsUseBoluoGoldCoin()));
                        cart.setUseBoluosilverCoin(DataStatus.valid.getKey().equals(p.getIsUseBoluoSilverCoin()));
                        cart.setUseCoupon(DataStatus.valid.getKey().equals(p.getIsUseCoupon()));
                        cart.setUseMemberDiscount(DataStatus.valid.getKey().equals(p.getIsUseMemberDiscount()));
                        cart.setDiscountMemberLevel(p.getMemberLevel());

                    } else {
                        throw new BaseException("没有找到商品信息");
                    }
                } else if (cart.getOrderType().equals(CardServiceTypeEnum.serviceItem.getKey())) {

                } else if (cart.getOrderType().equals(CardServiceTypeEnum.card.getKey())) {

                }
            }
        }

        //验证用户资料，折扣金额
        settle.setDiscountAmount(0L);
        settle.setDiscountRate(0L);
        CustomerVo customerVo = iCustomerInfoService.getNewCustomerVo(orderInfo.getCustomerUid());

        if (ObjectUtil.isEmpty(customerVo)) {
            throw new BaseException("没有找到用户信息");
        }

        settle.setMemberGrade(customerVo.getMemberGrade().longValue());
        logger.info("\n==========获取用户信息,折扣比例parameter:{}==========\n===========result:{}===========\n",
                settle.getCustomerId(), JSONObject.toJSONString(customerVo));

        settle.setCustomerInfo(customerVo);
        List<LevelAndPrivilege> list = customerVo.getLevelPrivilegeList();
        if (list != null && list.size() > 0) {
            for (LevelAndPrivilege cp : list) {
                if (CustomerLevelPrivilegeEnum.freeShipping.getKey().equals(cp.getPrivilegeName())) {
                    settle.setFreeFreight(Boolean.TRUE);
                    settle.setFreight(0L);
                    //break;
                } else if (CustomerLevelPrivilegeEnum.discount.getKey().equals(cp.getPrivilegeName())) {
                    //权益折扣，非百分制，这里做转换
                    logger.info("\n==========用户折扣值：{}=============\n", cp.getPrivilegeValue());
                    settle.setMemberDiscount(true);
                    settle.setDiscountRate(new BigDecimal(cp.getPrivilegeValue()).multiply(new BigDecimal(10)).longValue());
                }
            }
        }

        logger.info("\n==========折扣比例：{}，折扣金额：{}=========", settle.getDiscountRate(), settle.getDiscountAmount());

        //计算结算总额，积分
        //商品总额
        Long amount = 0L;
        //非活动商品总额
        Long normalShopAmount = 0L;
        //总积分
        Long score = 0L;

        //会员折扣
        Long disCount = 0L;
        for (OrderInfoItem cart : itemVoList) {
            amount += cart.getItemAmount();
            if (cart.getActivityUid() == null) {
                normalShopAmount += cart.getItemAmount();
            }
            if (cart.isUseMemberDiscount()) {
                if (cart.getDiscountMemberLevel().intValue() <= settle.getMemberGrade() && settle.getDiscountRate()>0) {
                    disCount += cart.getItemAmount() * (100 - settle.getDiscountRate()) / 100;
                }
            }
            if (cart.getPayByScore() == null) {
                cart.setPayByScore(0L);
            }
            score += cart.getPayByScore();
            if (cart.isUseBoluoGoldCoin()) {
                settle.setCanUseGoldCionAmount(cart.getItemAmount() + settle.getCanUseGoldCionAmount());
            }
            if (cart.isUseBoluosilverCoin()) {
                settle.setCanUseSilverCionAmount(cart.getItemAmount() + settle.getCanUseSilverCionAmount());
            }
            if (cart.isUseCoupon()) {
                settle.setCanUseCouponAmount(cart.getItemAmount() + settle.getCanUseCouponAmount());
            }
        }
        settle.setNormalShopAmount(normalShopAmount);
        settle.setShopAmount(amount);
        settle.setScoreAmount(score);
        settle.setDiscountAmount(disCount);
        logger.info("\n==========合计购物车金额，商品总额：{}，非活动商品总额：{}，结算总积分：{}=========",
                settle.getShopAmount(), settle.getNormalShopAmount(), settle.getScoreAmount());


        if (settle.getCanUseGoldCionAmount() == 0L) {
            settle.setBalance(0L);
        }
        if (settle.getCanUseSilverCionAmount() == 0L) {
            settle.setRedBag(0L);
        }
        if (settle.getCanUseCouponAmount() == 0L) {
            settle.setCouponId(null);
        }
        //验证优惠券资料
        checkCoupon(settle);

        //验证客户地址信息
        if (settle.getAddressId() != null) {
            CustomerAddressVo addressVo = checkAddress(settle);
            //会员没有包邮特权，需要计算邮费
            if (!settle.getFreeFreight()) {
                checkFreight(settle, addressVo, settle.getShopAmount());
            }
        } else {
            settle.setFreight(0L);
        }



        if (settle.getBalance() != null && settle.getBalance() > 0) {
            //settle.setBalance(settle.getBalance()*100);
            if (settle.getBalance() > settle.getCanUseGoldCionAmount()) {
                settle.setBalance(settle.getCanUseGoldCionAmount());
            }
            if (settle.getBalance() > customerFund.getBalance()) {
                throw new BaseException("金币不足" + MoneyUtils.changeF2Y(settle.getBalance()) + "元，不能结算");
            }
        }
        customerFund.setRedBag(0L);
        CustomerFundStore fundStore = customerFundStoreService.selectCustomerFund(orderInfo.getStoreId(), orderInfo.getCustomerUid());
        if (fundStore != null) {
            customerFund.setRedBag(fundStore.getRedBag());
        }
        if (settle.getRedBag() != null && settle.getRedBag() > 0) {
            if (fundStore == null || fundStore.getRedBag() < settle.getRedBag()) {
                throw new BaseException("银币不足" + MoneyUtils.changeF2Y(settle.getRedBag()) + "元，不能结算");
            }
            if (settle.getRedBag() > settle.getCanUseSilverCionAmount()) {
                settle.setRedBag(settle.getCanUseSilverCionAmount());
            }
        }
        if (settle.getScoreAmount() != null && settle.getScoreAmount() > 0) {
            if (settle.getScoreAmount() > customerFund.getScore()) {
                throw new BaseException("菠萝派不足" + settle.getScoreAmount() + "分，不能结算");
            }
        }


        //商品总额
        Long shopAmount = settle.getShopAmount();
        //物流费用
        Long fregiht = settle.getFreight();
        //折扣
        Long discount = settle.getDiscountAmount();
        if (discount == null) {
            discount = 0L;
        }

        //优惠金额
        Long coupon = settle.getCouponAmount();
        if (coupon == null) {
            coupon = 0L;
        }

        //积分
        if (score == null) {
            score = 0L;
        }
        //红包
        Long redBag = settle.getRedBag();
        if (redBag == null) {
            redBag = 0L;
        }
        //余额
        Long balance = settle.getBalance();
        if (balance == null) {
            balance = 0L;
        }

        rst.put("shopAmount", MoneyUtils.changeF2Y(shopAmount));
        if (fregiht > 0) {
            rst.put("freight", MoneyUtils.changeF2Y(fregiht));
        } else {
            rst.put("freight", "0.0");
        }

        if (discount > 0) {
            rst.put("discount", MoneyUtils.changeF2Y(discount));
        }

        if (coupon > 0) {
            rst.put("coupon", MoneyUtils.changeF2Y(coupon));
        }
        if (score > 0) {
            rst.put("score", score);
        }

        //付款金额
        Long payAmount = shopAmount + fregiht;
        rst.put("totalAmount", MoneyUtils.changeF2Y(payAmount));
        //优先使用银币抵扣
        if (redBag > 0) {
            if (redBag + discount + coupon - payAmount > 0) {
                redBag = payAmount - coupon - discount;
                rst.put("redBag", MoneyUtils.changeF2Y(redBag));
                balance = 0L;
                payAmount = 0L;
            } else {
                rst.put("redBag", MoneyUtils.changeF2Y(redBag));
                //payAmount = shopAmount + fregiht - discount - coupon - redBag;
            }
        }
        if (payAmount > 0) {
            payAmount = payAmount - discount - coupon - redBag;
            if (payAmount>0){
                if (payAmount>balance.longValue()){
                    payAmount -= balance.longValue();
                }else{
                    balance = payAmount.longValue();
                    payAmount = 0L;
                }
            }else{
                payAmount = 0L;
                balance = 0L;
            }
            /*
            if (payAmount < 0) {
                if (balance > 0) {
                    balance = balance + payAmount;
                }
                payAmount = 0L;
            }*/
        }

        if (balance > 0) {
            rst.put("balance", MoneyUtils.changeF2Y(balance));
        }
        rst.put("payAmount", MoneyUtils.changeF2Y(payAmount));

        if (settle.getNormalShopAmount() > 0 && settle.getCanUseCouponAmount() > 0) {
            rst.put("useCoupon", "1");
        } else {
            rst.put("useCoupon", "0");
        }

        if (customerFund.getRedBag() > 0 && settle.getCanUseSilverCionAmount() > 0 && coupon<=0) {
            rst.put("useRedBag", "1");
        } else {
            rst.put("useRedBag", "0");
        }

        if (customerFund.getBalance() > 0 && payAmount > 0 && settle.getCanUseGoldCionAmount() > 0) {
            rst.put("useBalance", "1");
        } else {
            if (balance == 0) {
                rst.put("useBalance", "0");
            } else {
                rst.put("useBalance", "1");
            }
        }

        if (settle.getScoreAmount() > 0) {
            rst.put("useScore", "1");
        } else {
            rst.put("useScore", "0");
        }

        return rst;
    }

    /**
     * 创建订单
     * 所有活动商品均不参与优惠券和折扣计算，活动商品为优惠商品
     *
     * @param settle
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject createOrder(OrderSettlementVo settle) throws Exception {
        if (!settle.isBatch()) {
            //用户层面限流
            limitUserOperation();
        }

        //settle.setScore(settle.getProductInfo().getJifen().longValue());
        //创建父订单
        OrderInfoParent parent = createParentOrder(settle);
        //创建子订单
        createChildOrder(settle, parent);

        //现金支付
        if (parent.getPayAmount() != null && parent.getPayAmount() > 0) {
            return callPayment(parent, settle);
        }

        //余额支付
        logger.info("===================开始余额支付=====================");
        parent.setPayStatus(PayStatusEnum.paid.getKey());
        parent.setPayTime(new Date());
        if (orderInfoParentService.updateOrderInfoParent(parent)) {
            orderPaymentSuccess(parent, null);
        }

        JSONObject object = new JSONObject();
        object.put("payStatus", PayStatusEnum.paid.getKey());
        return object;
    }

    /**
     * 修改订单
     * 所有活动商品均不参与优惠券和折扣计算，活动商品为优惠商品
     *
     * @param settle
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject editOrder(OrderSettlementVo settle) throws Exception {
        //用户层面限流
        limitUserOperation();

        if (settle.getScore() == null) {
            settle.setScore(0L);
        }
        //设置默认值
        settle.setCustomerId(SecurityUtils.getCustomerUid());
        //settle.setPlatformId(SecurityUtils.getCustomerPlatformUid());
        settle.setPlatSource(SecurityUtils.getCustomerSourcePort());

        settle.setCustomerId(SecurityUtils.getCustomerUid());
        settle.setPlatformId(SecurityUtils.getCustomerPlatformUid());

        OrderInfo orderInfo = this.getById(settle.getOrderId());
        //if (orderInfo == null || !orderInfo.getOrderStatus().equals(DataStatus.valid.getKey()) || orderInfo.getCustomerUid().longValue() != settle.getCustomerId()){
        if (orderInfo == null || !orderInfo.getOrderStatus().equals(DataStatus.valid.getKey())) {
            throw new BaseException("没有找到订单信息");
        }
        if (orderInfo.getPayStatus().equals(DataStatus.valid.getKey())) {
            throw new BaseException("该订单已支付");
        }


        List<OrderInfoItem> itemVoList = itemService.selectByOrderId(orderInfo.getOrderUid());
        if (itemVoList == null || itemVoList.size() == 0) {
            throw new BaseException("该订单没有需要结算的商品");
        }


        for (OrderInfoItem cart : itemVoList) {
            if (cart.getOrderType().equals(CardServiceTypeEnum.product.getKey())) {
                ProductInfoVo p = iProductInfoService.getProductDetail(cart.getProUid());
                if (p != null) {
                    if (!DataStatus.valid.getKey().equals(p.getDataStatus())) {
                        throw new BaseException("商品未上架，不能结算");
                    }
                    if (!DataStatus.valid.getKey().equals(p.getAuditStatus())) {
                        throw new BaseException("商品未上架，不能结算");
                    }
                    cart.setUseBoluoGoldCoin(DataStatus.valid.getKey().equals(p.getIsUseBoluoGoldCoin()));
                    cart.setUseBoluosilverCoin(DataStatus.valid.getKey().equals(p.getIsUseBoluoSilverCoin()));
                    cart.setUseCoupon(DataStatus.valid.getKey().equals(p.getIsUseCoupon()));
                    cart.setUseMemberDiscount(DataStatus.valid.getKey().equals(p.getIsUseMemberDiscount()));
                    cart.setDiscountMemberLevel(p.getMemberLevel());
                } else {
                    throw new BaseException("没有找到商品信息");
                }
            } else if (cart.getOrderType().equals(CardServiceTypeEnum.serviceItem.getKey())) {

            } else if (cart.getOrderType().equals(CardServiceTypeEnum.card.getKey())) {

            }
        }

        //验证用户资料，折扣金额
        settle.setDiscountAmount(0L);
        settle.setDiscountRate(0L);
        CustomerVo customerVo = iCustomerInfoService.getNewCustomerVo(orderInfo.getCustomerUid());

        if (ObjectUtil.isEmpty(customerVo)) {
            throw new BaseException("没有找到用户信息");
        }

        settle.setMemberGrade(customerVo.getMemberGrade().longValue());
        logger.info("\n==========获取用户信息,折扣比例parameter:{}==========\n===========result:{}===========\n",
                settle.getCustomerId(), JSONObject.toJSONString(customerVo));

        settle.setCustomerInfo(customerVo);
        List<LevelAndPrivilege> list = customerVo.getLevelPrivilegeList();
        if (list != null && list.size() > 0) {
            for (LevelAndPrivilege cp : list) {
                if (CustomerLevelPrivilegeEnum.freeShipping.getKey().equals(cp.getPrivilegeName())) {
                    settle.setFreeFreight(Boolean.TRUE);
                    settle.setFreight(0L);
                    //break;
                } else if (CustomerLevelPrivilegeEnum.discount.getKey().equals(cp.getPrivilegeName())) {
                    //权益折扣，非百分制，这里做转换
                    logger.info("\n==========用户折扣值：{}=============\n", cp.getPrivilegeValue());
                    settle.setMemberDiscount(true);
                    settle.setDiscountRate(new BigDecimal(cp.getPrivilegeValue()).multiply(new BigDecimal(10)).longValue());
                }
            }
        }

        logger.info("\n==========折扣比例：{}，折扣金额：{}=========", settle.getDiscountRate(), settle.getDiscountAmount());

        //计算结算总额，积分
        //商品总额
        Long amount = 0L;
        //非活动商品总额
        Long normalShopAmount = 0L;
        //总积分
        Long score = 0L;

        //会员折扣
        Long disCount = 0L;
        for (OrderInfoItem cart : itemVoList) {
            amount += cart.getItemAmount();
            if (cart.getActivityUid() == null) {
                normalShopAmount += cart.getItemAmount();
            }
            if (cart.isUseMemberDiscount()) {
                if (cart.getDiscountMemberLevel().intValue() <= settle.getMemberGrade() && settle.getDiscountRate()>0) {
                    disCount += cart.getItemAmount() * (100 - settle.getDiscountRate()) / 100;
                }
            }
            if (cart.getPayByScore() == null) {
                cart.setPayByScore(0L);
            }
            score += cart.getPayByScore();
            if (cart.isUseBoluoGoldCoin()) {
                settle.setCanUseGoldCionAmount(cart.getItemAmount() + settle.getCanUseGoldCionAmount());
            }
            if (cart.isUseBoluosilverCoin()) {
                settle.setCanUseSilverCionAmount(cart.getItemAmount() + settle.getCanUseSilverCionAmount());
            }
            if (cart.isUseCoupon()) {
                settle.setCanUseCouponAmount(cart.getItemAmount() + settle.getCanUseCouponAmount());
            }
        }
        settle.setNormalShopAmount(normalShopAmount);
        settle.setShopAmount(amount);
        settle.setScoreAmount(score);
        settle.setDiscountAmount(disCount);
        logger.info("\n==========合计购物车金额，商品总额：{}，非活动商品总额：{}，结算总积分：{}=========",
                settle.getShopAmount(), settle.getNormalShopAmount(), settle.getScoreAmount());


        if (settle.getCanUseGoldCionAmount() == 0L) {
            settle.setBalance(0L);
        }
        if (settle.getCanUseSilverCionAmount() == 0L) {
            settle.setRedBag(0L);
        }
        if (settle.getCanUseCouponAmount() == 0L) {
            settle.setCouponId(null);
        }
        //验证优惠券资料
        checkCoupon(settle);

        //验证客户地址信息
        if (settle.getAddressId() != null) {
            CustomerAddressVo addressVo = checkAddress(settle);
            //会员没有包邮特权，需要计算邮费
            if (!settle.getFreeFreight()) {
                checkFreight(settle, addressVo, settle.getShopAmount());
            }
        } else {
            settle.setFreight(0L);
        }

        //检验余额，积分或红包是否足够
        CustomerFundVo customerFund = null;
        CustomerFund fund = iCustomerFundService.getByCustomerId(orderInfo.getCustomerUid());
        if (ObjectUtil.isEmpty(fund)) {
            throw new BaseException("没有找到会员钱包信息");
        }
        customerFund = new CustomerFundVo();
        BeanUtils.copyProperties(fund, customerFund);
        logger.info("\n==========查询用户资金信息parameter:{}==========\n===========result:{}===========\n",
                settle.getCustomerId(), JSONObject.toJSONString(customerFund));

        if (settle.getBalance() != null && settle.getBalance() > 0) {
            if (settle.getBalance() > settle.getCanUseGoldCionAmount()) {
                settle.setBalance(settle.getCanUseGoldCionAmount());
            }
            if (settle.getBalance() > customerFund.getBalance()) {
                throw new BaseException("金币不足" + MoneyUtils.changeF2Y(settle.getBalance()) + "元，不能结算");
            }
        }
        customerFund.setRedBag(0L);
        CustomerFundStore fundStore = customerFundStoreService.selectCustomerFund(orderInfo.getStoreId(), orderInfo.getCustomerUid());
        if (fundStore != null) {
            customerFund.setRedBag(fundStore.getRedBag());
        }
        if (settle.getRedBag() != null && settle.getRedBag() > 0) {
            if (fundStore == null || fundStore.getRedBag() < settle.getRedBag()) {
                throw new BaseException("银币不足" + MoneyUtils.changeF2Y(settle.getRedBag()) + "元，不能结算");
            }
            if (settle.getRedBag() > settle.getCanUseSilverCionAmount()) {
                settle.setRedBag(settle.getCanUseSilverCionAmount());
            }
        }
        if (settle.getScoreAmount() != null && settle.getScoreAmount() > 0) {
            if (settle.getScoreAmount() > customerFund.getScore()) {
                throw new BaseException("菠萝派不足" + settle.getScoreAmount() + "分，不能结算");
            }
        }

        if (settle.getBalance() != null && settle.getBalance() > 0L) {
            if (settle.getBalanceDetail() == null || settle.getBalanceDetail().size() == 0) {
                throw new BaseException("请选择支付金币的门店");
            }
            Long balance = 0L;
            for (BalanceItemVo vo : settle.getBalanceDetail()) {
                CustomerFundStore store = customerFundStoreService.selectCustomerFund(vo.getStoreId(), orderInfo.getCustomerUid());
                if (store == null || store.getBalance() < vo.getBalance()) {
                    throw new BaseException("所选门店金币不足，请重新选择");
                }
                balance += vo.getBalance();
            }
            if (balance < settle.getBalance()) {
                throw new BaseException("所选门店金币之和需要等于支付金币");
            }
        }

        if (settle.getCanUseGoldCionAmount() == 0L) {
            settle.setBalance(0L);
        }
        if (settle.getCanUseSilverCionAmount() == 0L) {
            settle.setRedBag(0L);
        }
        if (settle.getCanUseCouponAmount() == 0L) {
            settle.setCouponId(null);
        }


        if (PayMethodEnum.wechat.getKey().equals(settle.getPayMethod())) {
            if (StringUtils.isEmpty(SecurityUtils.getCustomerMchId())) {
                throw new BaseException("请配置应用的商户号再结算");
            }
        }

        settle.setIsRecharge(OrderRechargeEnum.good.getKey());

        OrderInfoParent parent = orderInfoParentService.getParent(orderInfo.getParentOrderNo());
        parent.setParentAmount(settle.getShopAmount());
        parent.setDiscountRate(settle.getDiscountRate());
        parent.setDiscountAmount(settle.getDiscountAmount());
        parent.setFreightAmount(settle.getFreight());
        parent.setPayByBalance(settle.getBalance());
        parent.setPayByRedBag(settle.getRedBag());
        parent.setPayByScore(settle.getScore());
        parent.setUseCouponUid(settle.getCouponId());
        parent.setUseCouponAmount(settle.getCouponAmount());
        parent.setPayAmount(settle.getShopAmount()-settle.getCouponAmount()-settle.getDiscountAmount()-settle.getRedBag()-settle.getBalance());
        if (parent.getPayAmount()<0L){
            parent.setPayAmount(0L);
        }

        //修改子订单
        OrderSettleTotalVo totalVo = new OrderSettleTotalVo();
        totalVo.setBalance(parent.getPayByBalance());
        totalVo.setCouponAmount(parent.getUseCouponAmount());
        totalVo.setCouponRate(settle.getCouponRate());
        totalVo.setDiscountAmount(parent.getDiscountAmount());
        totalVo.setDiscountRate(parent.getDiscountRate());
        totalVo.setRedBag(parent.getPayByRedBag());
        totalVo.setScore(parent.getPayByScore());
        totalVo.setFreightAmount(parent.getFreightAmount());
        parent.setParentOrderNo(parent.getParentOrderNo()+"0");


        //保存非供应商子订单
        updateChildOrder(settle, parent, totalVo, itemVoList, orderInfo);

        //现金支付
        if (parent.getPayAmount() != null && parent.getPayAmount() > 0) {
            if (orderInfoParentService.updateOrderInfoParent(parent)) {
                return callPayment(parent, settle);
            }else{
                throw new BaseException("订单保存失败，请重试");
            }
        }

        //余额支付
        logger.info("===================开始余额支付=====================");
        parent.setPayStatus(PayStatusEnum.paid.getKey());
        parent.setPayTime(new Date());
        if (orderInfoParentService.updateOrderInfoParent(parent)) {
            orderPaymentSuccess(parent, null);
            CustomerVo cust = iCustomerInfoService.getCustomerVo(parent.getCustomerId());
            if (ObjectUtil.isNotEmpty(cust))
                newOrderNotice(parent, cust);
        }

        JSONObject object = new JSONObject();
        object.put("payStatus", PayStatusEnum.paid.getKey());
        return object;
    }

    @Override
    public JSONObject createExchangeOrder(OrderSettlementVo settle) throws Exception {
        //用户层面限流
        limitUserOperation();

        //设置默认值
        settle.setCustomerId(SecurityUtils.getCustomerUid());
        //settle.setPlatformId(SecurityUtils.getCustomerPlatformUid());
        settle.setPlatSource(SecurityUtils.getCustomerSourcePort());


        //根据客户地址和客户权利计算邮费
        if (settle.getAddressId() != null) {
            CustomerAddressVo addressVo = checkAddress(settle);
        }


        settle.setIsRecharge(OrderRechargeEnum.good.getKey());

        //创建父订单
        OrderInfoParent parent = createExchangeParentOrder(settle);



        JSONObject object = new JSONObject();
        object.put("payStatus", PayStatusEnum.paid.getKey());
        return object;
    }

    /**
     * 微信支付回调
     *
     * @param jsonObject
     * @return
     */
    @Override
    public boolean wechatPaymentCallBack(JSONObject jsonObject) {
        logger.info("\n================支付回调json:{}============\n", jsonObject);
        String out_trade_no = jsonObject.getString("out_trade_no");
        logger.info("\n================out_trade_no={}===========\n", out_trade_no);
        //如果没有订单号，直接返回，不处理任何逻辑
        if (StringUtils.isEmpty(out_trade_no)) {
            return true;
        }
        //防止重复调用，重复赠送
        String key = CachePrefix.PRE_GLOABLE+"wechatPaymentCallBack_"+out_trade_no;
        if (redisService.incr(key,3,TimeUnit.SECONDS)>1){
            return false;
        }
        //还没有支付过
        if (orderPayInfoService.getOrderPayInfo(out_trade_no, PayMethodEnum.wechat.getKey()) == null) {
            logger.info("\n================保存微信的支付记录============\n", jsonObject);
            String parentOrderNo = out_trade_no;
            Long orderItemUid = 0L;
            if (parentOrderNo.lastIndexOf("_")>0){
                parentOrderNo = parentOrderNo.substring(0,parentOrderNo.lastIndexOf("_"));
                orderItemUid = Long.parseLong(out_trade_no.substring(out_trade_no.lastIndexOf("_")+1));
            }
            OrderInfoParent parent = orderInfoParentService.getOrderInfo(parentOrderNo);

            if (parent != null) {
                if (!orderPayInfoService.insertWechatOrderPayInfo(jsonObject, parent)) {
                    logger.info("\n================保存微信支付记录失败:{}============\n", jsonObject);
                    redisService.deleteObject(key);
                    return false;
                }

                if (PayStatusEnum.unpaid.getKey().equals(parent.getPayStatus())) {
                    parent.setPayStatus(PayStatusEnum.paid.getKey());
                    parent.setPayTime(new Date());
                    parent.setProfitSharing(ProfitSharingEnum.N.toString());
                    if (orderInfoParentService.updateOrderInfoParent(parent)) {
                        orderPaymentSuccess(parent, jsonObject);
                        redisService.deleteObject(key);
                        //return true;
                    }
                    //throw new BaseException("修改订单{" + out_trade_no + "}支付状态发生错误，需要重新修改");
                }else{
                    //如果是已经支付了，且是后台创建的，那么可能是多次收款
                    if (OrderRechargeEnum.admin.getKey().equals(parent.getIsRecharge())) {
                        List<OrderInfo> orders = selectChildOrderByParentOrderNo(parent.getParentOrderNo());
                        Set<Long> orderIds = new HashSet<Long>();
                        Long payAmount = jsonObject.getJSONObject("amount").getLong("payer_total");
                        for (OrderInfo oi : orders) {
                            oi.setPayStatus(parent.getPayStatus());
                            oi.setPayTime(parent.getPayTime());
                            oi.setPayMethod(parent.getPayMethod());
                            oi.setPayAmount(oi.getPayAmount()+payAmount);
                            oi.setProfitSharing(ProfitSharingEnum.N.toString());
                            oi.setIsShared("0");
                            oi.setSendStatus(SendStatusEnum.receive.getKey());
                            oi.setSendTime(parent.getPayTime());
                            oi.setOrderPackStatus(PackStatusEnum.voted.getKey());
                            oi.setReceiveTime(parent.getPayTime());
                            oi.setCommentStatus(CommentStatusEnum.comment.getKey());
                            orderIds.add(oi.getOrderUid());
                            this.saveOrUpdate(oi);
                        }
                    }
                }
                if (orderItemUid>0L){
                    OrderInfoItem item = itemService.getById(orderItemUid);
                    if (item != null){
                        item.setPayStatus("1");
                        item.setPayDate(new Date());
                        itemService.updateById(item);
                    }
                }
                return true;
            }
        }
        return true;
    }


    /**
     * 订单支付成功
     *
     * @param parent
     */
    private void orderPaymentSuccess(OrderInfoParent parent, JSONObject jsonObject) {
        //更新优惠券的状态为已使用
        if (OrderRechargeEnum.good.getKey().equals(parent.getIsRecharge())) {
            List<OrderInfo> orders = selectChildOrderByParentOrderNo(parent.getParentOrderNo());
            Set<Long> orderIds = new HashSet<Long>();
            for (OrderInfo oi : orders) {
                oi.setPayStatus(parent.getPayStatus());
                oi.setPayTime(parent.getPayTime());
                oi.setPayMethod(parent.getPayMethod());

                oi.setProfitSharing(ProfitSharingEnum.N.toString());
                oi.setIsShared("0");

                oi.setSendStatus(SendStatusEnum.receive.getKey());
                oi.setSendTime(parent.getPayTime());
                oi.setOrderPackStatus(PackStatusEnum.voted.getKey());
                oi.setReceiveTime(parent.getPayTime());
                oi.setCommentStatus(CommentStatusEnum.comment.getKey());

                orderIds.add(oi.getOrderUid());
                this.saveOrUpdate(oi);
            }

            /**
             * 获取订单明细列表
             */
            List<OrderInfoItem> items = itemService.select(new ArrayList<Long>(orderIds));

            //修改商品库存
            updateProductData(items);

            //扣余额，积分等
            deductionCustomerFund(parent, items);

        } else if (OrderRechargeEnum.recharge.getKey().equals(parent.getIsRecharge())) {
            //充值订单:充值会员+充值余额============================================
            OrderRecharge recharge = rechargeService.getByParentOrderNo(parent.getParentOrderNo());
            if (recharge == null || recharge.getPayStatus().equals(PayStatusEnum.paid.getKey())) {
                return;
            }
            recharge.setPayStatus(PayStatusEnum.paid.getKey());
            recharge.setPayTime(parent.getPayTime());
            if (rechargeService.updateById(recharge)) {
                CustomerFundVo fundVo = new CustomerFundVo();
                fundVo.setCustomerUid(parent.getCustomerId());
                fundVo.setBizNo(recharge.getRechargeNo());
                fundVo.setBizTime(recharge.getPayTime());
                fundVo.setStatus(DataStatus.valid.getKey());
                if(recharge.getRechargeId() != null) {
                    fundVo.setBizDesc("升级VIP");
                }else{
                    fundVo.setBizDesc("扫码兑换");
                }
                fundVo.setRemark(recharge.getRechargeName());
                fundVo.setOrderUid(recharge.getRechargeUid());
                fundVo.setPlatformUid(recharge.getPlatformUid());
                if (recharge.getScore() != null && recharge.getScore() > 0) {
                    fundVo.setScore(recharge.getScore());
                }
                //涨积分
                iCustomerFundService.addCustomerFund(fundVo);

                //如果有VIP，需要赠送VIP
                if (recharge.getLevelId() != null){
                    CustomerLevelInfo cli = new CustomerLevelInfo();
                    cli.setCustomerUid(parent.getCustomerId());
                    cli.setLevelUid(recharge.getLevelId());
                    cli.setStatus(DataStatus.valid.getKey());
                    cli.setScore(0L);
                    cli.setCreateTime(new Date());
                    customerLevelInfoService.save(cli);
                    List<LevelAndPrivilege> list = customerPrivilegeService.getLevelAndPrivilege(recharge.getLevelId());
                    for (LevelAndPrivilege lp:list) {
                        if ("points".equalsIgnoreCase(lp.getPrivilegeName())){
                            fundVo = new CustomerFundVo();
                            fundVo.setCustomerUid(parent.getCustomerId());
                            fundVo.setBizNo(recharge.getRechargeNo());
                            fundVo.setBizTime(recharge.getPayTime());
                            fundVo.setStatus(DataStatus.valid.getKey());
                            fundVo.setBizDesc("升级VIP赠送积分");
                            fundVo.setRemark(recharge.getRechargeName());
                            fundVo.setOrderUid(recharge.getRechargeUid());
                            fundVo.setPlatformUid(recharge.getPlatformUid());
                            fundVo.setScore(Long.parseLong(lp.getPrivilegeValue()));
                            iCustomerFundService.addCustomerFund(fundVo);
                        }else if ("paiban".equalsIgnoreCase(lp.getPrivilegeName())){
                            fundVo = new CustomerFundVo();
                            fundVo.setCustomerUid(parent.getCustomerId());
                            fundVo.setBizNo(recharge.getRechargeNo());
                            fundVo.setBizTime(recharge.getPayTime());
                            fundVo.setStatus(DataStatus.valid.getKey());
                            fundVo.setBizDesc("升级VIP赠送排版次数");
                            fundVo.setRemark(recharge.getRechargeName());
                            fundVo.setOrderUid(recharge.getRechargeUid());
                            fundVo.setPlatformUid(recharge.getPlatformUid());
                            fundVo.setRedBag(Long.parseLong(lp.getPrivilegeValue()));
                            iCustomerFundService.addCustomerFund(fundVo);
                        }
                    }
                }

            }

        } else if (OrderRechargeEnum.admin.getKey().equals(parent.getIsRecharge())) {
            List<OrderInfo> orders = selectChildOrderByParentOrderNo(parent.getParentOrderNo());
            Set<Long> orderIds = new HashSet<Long>();
            Long payAmount = jsonObject.getJSONObject("amount").getLong("payer_total");
            for (OrderInfo oi : orders) {
                oi.setPayStatus(parent.getPayStatus());
                oi.setPayTime(parent.getPayTime());
                oi.setPayMethod(parent.getPayMethod());
                oi.setPayAmount(payAmount);
                oi.setProfitSharing(ProfitSharingEnum.N.toString());
                oi.setIsShared("0");
                oi.setSendStatus(SendStatusEnum.receive.getKey());
                oi.setSendTime(parent.getPayTime());
                oi.setOrderPackStatus(PackStatusEnum.voted.getKey());
                oi.setReceiveTime(parent.getPayTime());
                oi.setCommentStatus(CommentStatusEnum.comment.getKey());
                orderIds.add(oi.getOrderUid());
                this.saveOrUpdate(oi);
            }

        }

    }

    public void testAddWeiXinProfitReceiver() {
        PlatformStore store = platformStoreService.getById(18L);
        if (store != null && StringUtils.isNotEmpty(store.getMerchantId()) && StringUtils.isNotEmpty(store.getMerchantName())) {
            //v3ProfitsharingReceiversAdd();
            addWeiXinProfitReceiver(null, store);
        }
    }

    /**
     * 添加分账接受方
     */
    private boolean addWeiXinProfitReceiver(OrderInfoParent orderInfo, PlatformStore store) {
        /*
        logger.info("开始添加收账方=====>{}", JSONObject.toJSON(orderInfo));
        ProfitShareVo profit = new ProfitShareVo();
        try {
            profit.setSub_mchid(WechatV3Payment.sub_mchid);
            profit.setType(ProfitsharingAddTypeEnum.MERCHANT_ID.name());
            profit.setAccount(store.getMerchantId().trim());
            profit.setName(store.getMerchantName().trim());
            profit.setRelation_type(ProfitsharingRelationTypeEnum.SERVICE_PROVIDER.name());
            ProfitShareVo response = WechatV3Payment.V3ProfitsharingReceiversAdd(profit);
            orderInfoShareService.save(orderInfo.getParentOrderNo(), "", ProfitSharingActionEnum.receiversAdd.name(), 0L, profit, response);
            if (response != null && StringUtils.isEmpty(response.getCode())) {
                return true;
            }
        } catch (Exception e) {
            logger.error("执行添加接收方微信分账异常==>", e);
            e.printStackTrace();
        }

        return false;

         */
        //后续不用分账，每个门店单独收款 update by liuhj 2024-03-13
        return true;
    }

    //余额支付，积分计算
    private void balanceScore(OrderInfoParent parent) {
        logger.info("==========余额支付，开始积分计算==========");
        Long customerId = parent.getCustomerId();
        CustomerVo customer = iCustomerInfoService.getCustomerVo(customerId);
        if (customer == null || customer.getCustomerLevelVo() == null) {
            return;
        }
        //积分倍数可能是小数，自购默认1：1积分
        double score = 1.0;
        //默认一块钱一积分，最终以店铺设置为准，自购算积分，其他暂时不算积分
        Long goodsIntegral = 1L;

        List<com.probox.customer.api.domain.CustomerLevelPrivleageVo> lpList = customer.getCustomerLevelVo().getCustomerLevelPrivleageVos();
        for (com.probox.customer.api.domain.CustomerLevelPrivleageVo pv : lpList) {
            if (CustomerLevelPrivilegeEnum.multiplePoints.getKey().equals(pv.getPrivleageName())) {
                score = Double.parseDouble(pv.getPrivilegeValue());
                break;
            }
        }
        if (ObjectUtil.isEmpty(score) || score == 0) score = 1.0;
        logger.info("\n===========自购积分倍率:{}===========\n", score);
        PlatformGeneralsettingsVo data = platformGeneralsettingsService.get(customer.getPlatformUid());
        if (ObjectUtil.isNotEmpty(data)) {
            //一块钱对应多少积分
            goodsIntegral = Long.parseLong(data.getGoodsIntegral());
            if (ObjectUtil.isEmpty(goodsIntegral) || goodsIntegral == 0) goodsIntegral = 1L;
        }

        if (score > 0) {
            List<OrderInfo> list = parent.getOrderInfoList();
            for (OrderInfo orderInfo : list) {
                CustomerFundVo fundVo = new CustomerFundVo();
                fundVo.setPlatformUid(customer.getPlatformUid());
                fundVo.setBizTime(parent.getPayTime());
                fundVo.setOrderUid(orderInfo.getOrderUid());
                fundVo.setBizNo(orderInfo.getOrderNo());
                fundVo.setFromCustomerId(customerId);
                fundVo.setCustomerUid(customer.getCustomerUid());
                fundVo.setScore(new Double(score * ((orderInfo.getPayAmount() + orderInfo.getPayByBalance()) * 0.01) * goodsIntegral).longValue());
                List<OrderInfoItem> items = orderInfo.getOrderInfoItemList();
                StringBuffer remark = new StringBuffer();
                for (OrderInfoItem item : items) {
                    remark.append(item.getProName()).append("   ").append(item.getPayAmountStr()).append("\n");
                }
                fundVo.setRemark(remark.toString());
                fundVo.setStatus(CustomerFundStatusEnum.freeze.getKey());
                logger.info("\n===========购买获得积分：{}，积分倍率：{},一元等于{}积分===========\n", fundVo.getScore(), score, goodsIntegral);
                if (fundVo.getScore() > 0) {
                    logger.info("\n===========远程调用增加客户资金接口参数:{}===========\n", fundVo);
                    iCustomerFundService.addCustomerFund(fundVo);
                    //logger.info("\n===========远程调用增加客户资金接口返回结果:{}===========\n", JSON.toJSONString(r1));
                }
            }
        }
    }


    /**
     * 微信分账，解冻剩余资金
     */
    @Override
    public void v3ProfitsharingOrdersUnfreeze(String subMchid, String transactionId, String orderNo) {
        if (StringUtils.isEmpty(subMchid)) {
            logger.error("未执行订单号:{}解冻微信分账剩余资金，该订单子商户号为空", orderNo);
            return;
        }
        if (StringUtils.isEmpty(transactionId)) {
            logger.error("未执行订单号:{}解冻微信分账剩余资金，该订单交易流水号为空", orderNo);
            return;
        }
        ProfitShareVo profit = new ProfitShareVo();
        try {
            profit.setSub_mchid(subMchid);
            profit.setTransaction_id(transactionId);
            profit.setOut_order_no(orderNo);
            profit.setDescription("释放剩余资金");
            WechatV3Payment.V3ProfitsharingOrdersUnfreeze(profit);
        } catch (Exception e) {
            logger.error("执行解冻微信分账剩余资金异常==>", e);
            e.printStackTrace();
        }

    }

    /**
     * 计算客户分润
     *
     * @param parent
     */
    private void customerProfit(OrderInfoParent parent, JSONObject jsonObject) {
        logger.info("\n===========开始计算客户分润===========\n");
        Long customerId = parent.getCustomerId();
        CustomerVo customerVo = iCustomerInfoService.getCustomerVo(customerId);
        //分账标识,需要分账则添加分账方，不需要分账则立即解冻资金
        boolean customerFlag = giveProfit(parent, customerVo, customerId, jsonObject);
        if (parent.getOrderInfoList().size() > 0) {
            OrderInfo orderInfo = parent.getOrderInfoList().get(0);
            if (orderInfo.getPayAmount() > 0 && orderInfo.getProfitSharing().equals(ProfitSharingEnum.Y.toString())) {
                if (orderInfo.getStoreId() != null) {
                    PlatformStore store = platformStoreService.getById(orderInfo.getStoreId());
                    if (store != null && StringUtils.isNotEmpty(store.getMerchantId()) && StringUtils.isNotEmpty(store.getMerchantName())) {
                        addWeiXinProfitReceiver(parent, store);
                    }
                }
            } else {
                //v3ProfitsharingOrdersUnfreeze(jsonObject.getString("sub_mchid"), jsonObject.getString("transaction_id"), parent.getParentOrderNo());
            }
        }

    }

    /**
     * 新订单通知
     *
     * @param parent
     * @param customerVo
     */
    private void newOrderNotice(OrderInfoParent parent, CustomerVo customerVo) {
        if (customerVo != null) {
            String page = "";
            String proName = "";
            String consigneeName = "";
            //MessageEntity entity = null;
            WechatInfomation infomation = null;
            WeChatInfomationOrder infomationOrder = null;

            CustomerAddressVo customerAddressInfo = iCustomerAddressService.getCustomerAddressInfo(parent.getOrderInfoList().get(0).getAddressUid());
            if (ObjectUtil.isNotEmpty(customerAddressInfo)) {
                consigneeName = customerAddressInfo.getName();
            } else
                consigneeName = parent.getOrderInfoList().get(0).getCustomerName();


            for (OrderInfo order : parent.getOrderInfoList()) {
                page = "pages/orderDetail/orderDetail?orderUid=" + order.getOrderUid();

                if (ObjectUtil.isNotEmpty(order.getOrderInfoItemList()))
                    proName = order.getOrderInfoItemList().get(0).getProName();

                infomationOrder = new WeChatInfomationOrder();
                infomationOrder.setProName(proName);
                infomationOrder.setOrderNo(order.getOrderNo());
                infomationOrder.setOrderMoney(order.getPayAmountStr());
                infomationOrder.setConsigneeName(consigneeName);
                infomationOrder.setCreateTime(DateUtil.formatDateTime(order.getCreateTime()));

                infomation = new WechatInfomation();
                infomation.setPage(page);
                infomation.setData(infomationOrder);
                infomation.setTouser(customerVo.getOpenID());
                infomation.setInfomationType(WechatInfomationEnum.newOrder.getValue());


            }
        }
    }

    /**
     * 分润计算，现金支付。
     *
     * @param parent
     * @param customer
     * @param fromUserId
     */
    private boolean giveProfit(OrderInfoParent parent, CustomerVo customer, Long fromUserId, JSONObject jsonObject) {
        if (customer == null) {
            return false;
        }
        logger.info("\n===========经验计算，客户:{}===========\n", customer);
        Long profitRate = Constants.PROFIT_RATE;
        //积分倍数可能是小数
        double score = 1.0;
        if (customer.getCustomerLevelVo() != null) {
            List<CustomerLevelPrivleageVo> lpList = customer.getCustomerLevelVo().getCustomerLevelPrivleageVos();
            for (CustomerLevelPrivleageVo pv : lpList) {
                if (CustomerLevelPrivilegeEnum.multiplePoints.getKey().equals(pv.getPrivleageName())) {
                    score = Double.parseDouble(pv.getPrivilegeValue());
                    break;
                }
            }
            if (ObjectUtil.isEmpty(score) || score == 0) score = 1.0;
        }

        //有利润可以分或可以积分
        if ((profitRate != null && profitRate > 0) || (score > 0)) {
            List<OrderInfo> list = parent.getOrderInfoList();
            for (OrderInfo orderInfo : list) {
                CustomerFundVo fundVo = new CustomerFundVo();
                fundVo.setPlatformUid(customer.getPlatformUid());
                fundVo.setBizTime(orderInfo.getPayTime());
                fundVo.setOrderUid(orderInfo.getOrderUid());
                fundVo.setBizNo(orderInfo.getOrderNo());
                fundVo.setFromCustomerId(fromUserId);
                fundVo.setCustomerUid(customer.getCustomerUid());
                fundVo.setStoreId(orderInfo.getStoreId());
                fundVo.setScore(new Double(score * ((orderInfo.getPayAmount()) * 0.01)).longValue());
                fundVo.setProfit(new Double(profitRate * 0.01 * orderInfo.getPayAmount()).longValue());
                List<OrderInfoItem> items = orderInfo.getOrderInfoItemList();
                StringBuffer remark = new StringBuffer();
                for (OrderInfoItem item : items) {
                    remark.append(item.getProName()).append("   ").append(item.getPayAmountStr()).append("\n");
                }
                fundVo.setRemark(remark.toString());
                fundVo.setStatus(CustomerFundStatusEnum.valid.getKey());
                logger.info("\n===========计算经验金额:{},购买获得积分：{}，积分倍率：{}===========\n", fundVo.getProfit(), fundVo.getScore(), score);
                if (fundVo.getProfit() > 0 || fundVo.getScore() > 0) {
                    logger.info("\n===========远程调用增加客户资金接口参数:{}===========\n", fundVo);
                    iCustomerFundService.addCustomerFund(fundVo);
                    // logger.info("\n===========远程调用增加客户资金接口返回结果:{}===========\n", JSON.toJSONString(r1));
                }
            }
            return true;
        }
        return false;
    }

    /**
     * 扣除使用余额、积分、红包支付
     *
     * @param parent
     */
    private void deductionCustomerFund(OrderInfoParent parent, List<OrderInfoItem> items) {
        logger.info("\n=========支付成功开始扣减用户余额,积分等============\n");
        CustomerFundVo fundVo = new CustomerFundVo();
        fundVo.setCustomerUid(parent.getCustomerId());
        boolean update = false;

        if (parent.getPayByScore() != null && parent.getPayByScore() > 0) {
            fundVo.setScore(parent.getPayByScore());
            update = true;
        }

        if (update) {
            fundVo.setRemark(items.get(0).getProName());
            fundVo.setBizNo(parent.getParentOrderNo());
            fundVo.setOrderUid(parent.getParentUid());
            fundVo.setBizTime(parent.getPayTime());
            fundVo.setPlatformUid(parent.getPlatformId());
            fundVo.setStatus(CustomerFundStatusEnum.valid.getKey());
            fundVo.setStoreId(parent.getStoreId());
            if (items.get(0).getOrderType().equals("good")) {
                fundVo.setBizDesc("下载论文");
            }else if (items.get(0).getOrderType().equals("maiduan")){
                fundVo.setBizDesc("买断论文");
            }else{
                fundVo.setBizDesc("消耗积分");
            }
            iCustomerFundService.deductionCustomerFund(fundVo);
        }
    }

    /**
     * 修改商品库存，修改活动库存remoteCustomerService.deductionCustomerFund
     *
     * @param items
     */
    private void updateProductData(List<OrderInfoItem> items) {

        for (OrderInfoItem item : items) {
            //如果产品ID不等于空，则需要扣减产品库存
            if (item.getProUid() != null) {
                //如果是下载论文
                if (item.getOrderType().equals("good")) {
                    iProductInfoService.incProductDownloadCount(item.getProUid());
                }else if (item.getOrderType().equals("maiduan")){
                    //如果是买断
                    iProductInfoService.incProductBuyCount(item.getProUid());
                }

            }
        }
    }


    /**
     * 通过父订单号，查询子订单列表
     *
     * @param orderNo
     * @return
     */
    private List<OrderInfo> selectChildOrderByParentOrderNo(String orderNo) {
        QueryWrapper<OrderInfo> queryWrapper = Wrappers.query();
        queryWrapper.eq("PARENT_ORDER_NO", orderNo);
        return this.orderInfoMapper.selectList(queryWrapper);
    }


    /**
     * 查询父订单下所有的子订单
     */
    private List<OrderInfo> queryOrderByParent(String parentOrderNo) {
        QueryWrapper<OrderInfo> queryWrapper = Wrappers.query();
        queryWrapper.eq("PARENT_ORDER_NO", parentOrderNo);
        queryWrapper.eq("ORDER_STATUS", OrderStatusEnum.effect.getKey());
        return orderInfoMapper.selectList(queryWrapper);
    }

    /**
     * 继续支付
     *
     * @param settle
     * @return
     */
    @Override
    public JSONObject toPay(OrderSettlementVo settle) {
        if (ObjectUtil.isEmpty(settle.getParentOrderNo()))
            throw new BaseException("支付单号不能为空");

        OrderInfoParent parent = orderInfoParentService.getParent(settle.getParentOrderNo());
        if (parent != null) {
            OrderQuery query = new OrderQuery();
            query.setCustomerUid(SecurityUtils.getCustomerUid());
            query.setParentOrderNo(parent.getParentOrderNo());
            if (orderInfoItemPayService.validateBalanceAndRedbag(query).longValue() > 0) {
                throw new BaseException("门店金币或银币不足，请重新下单支付");
            }
            settle.setPayMethod(parent.getPayMethod());
            return callPayment(parent, settle);
        } else
            throw new BaseException("没有找到支付订单信息");

    }

    /**
     * 根据商品ID查询未付款订单及其他子订单
     *
     * @param query
     * @return
     */
    @Override
    public List<OrderMergeDetailVo> getOrderByProId(OrderQuery query) {
        if (ObjectUtil.isEmpty(query.getProUid()))
            throw new BaseException("商品ID不能为空");

        OrderMergeDetailVo detailVo = null;
        List<OrderMergeDetailVo> voList = null;

        List<Long> list = itemService.getByProId(query);
        if (ObjectUtil.isNotEmpty(list)) {
            OrderInfo orderInfo = null;
            voList = new ArrayList<>();

            for (Long orderUid : list) {
                orderInfo = this.getById(orderUid);
                //取未支付且有效地订单
                if (orderInfo != null && OrderStatusEnum.effect.getKey().equals(orderInfo.getOrderStatus())
                        && PayStatusEnum.unpaid.getKey().equals(orderInfo.getPayStatus())
                        && OrderTypeEnum.good.getKey().equals(orderInfo.getOrderType())) {

                    detailVo = new OrderMergeDetailVo();
                    BeanUtils.copyProperties(orderInfo, detailVo);

                    detailVo.setParentOrderNo(orderInfo.getParentOrderNo());
                    detailVo.setActualAmount(detailVo.getPayAmount() + detailVo.getFreightAmount());

                    OrderInfoParent parent = orderInfoParentService.getParent(orderInfo.getParentOrderNo());

                    //判断是否合并支付
                    List<OrderInfo> infoList = queryOrderByParent(orderInfo.getParentOrderNo());
                    detailVo.setIsMergePay("0");
                    if (infoList != null && infoList.size() > 1)
                        detailVo.setIsMergePay("1");

                    voList.add(detailVo);
                }
            }
        }
        return voList;
    }

    protected String getSubMchId(Long storeId){
        String sub_mchid = WechatV3Payment.sub_default_mchid;
        if (storeId != null) {
            PlatformStore store = platformStoreService.getById(storeId);
            if (store != null && StringUtils.isNotEmpty(store.getMerchantId())) {
                sub_mchid = store.getMerchantId();
            }
        }
        return sub_mchid;
    }


    @Override
    public JSONObject addPayInfo(OrderInfo orderInfo,OrderInfoItem item){
        OrderInfoParent parent = new OrderInfoParent();
        parent.setParentOrderNo(orderInfo.getParentOrderNo()+"_"+item.getItemUid());
        parent.setPayAmount(item.getPayAmount());
        OrderSettlementVo settle = new OrderSettlementVo();
        settle.setPayMethod("wechat");
        return callPayment(parent,settle);
    }

    /**
     * 调用支付，统一下单
     *
     * @param parent
     * @param settle
     */
    private JSONObject callPayment(OrderInfoParent parent, OrderSettlementVo settle) {
        if (PayMethodEnum.wechat.getKey().equals(settle.getPayMethod())) {
            logger.info("=================调用支付，统一下单===================");
            //总金额规则校验，最小值为1
            if (parent != null && parent.getPayAmount() != null && parent.getPayAmount() > 0) {
                //微信支付
                return wechatPayment(parent, settle, false);
                //throw new BaseException("系统升级中，暂不支持微信付款，请联系客服下单。");
            }
            return null;
        }
        throw new BaseException("无效的支付方式");
    }

    /**
     * 微信支付
     *
     * @param parent
     * @param settle
     */
    private JSONObject wechatPayment(OrderInfoParent parent, OrderSettlementVo settle, boolean flag) {
        WxPayRequestBo wxPayRequestBo = new WxPayRequestBo()
                .setAppid(WechatV3Payment.appid)
                .setMchid(WechatV3Payment.mchid)
                .setDescription(WechatV3Payment.desc)
                .setOut_trade_no(parent.getParentOrderNo())
                .setNotify_url(WechatV3Payment.notify_url)
                .setAmount(new WxPaymentAmount(parent.getPayAmount()))
                .setSettle_info(new WxPayRequestSettleInfo(flag));

        //logger.info("=============支付来源：{}============", settle.getPlatSource());


        String wxPayRequestJsonStr = JSONUtil.toJsonStr(wxPayRequestBo);
        try {
            //第一步获取prepay_id
            String prepayId = WechatV3Payment.V3PayPartnerTransactionsJsapi(wxPayRequestJsonStr);
            //第二步获取调起支付的参数
            JSONObject object = new JSONObject();
            object.put("code_url",prepayId);
            object.put("orderNo",parent.getParentOrderNo());
            return object;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }


    /**
     * 限制用户对订单的操作频率
     */
    private void limitUserOperation() {
        String key = user_operator_limit_key + SecurityUtils.getCustomerUid();
        if (redisService.incr(key, user_operator_limit_time, TimeUnit.SECONDS) > user_operator_limit) {
            throw new BaseException(MessageConstants.MSG_FAST);
        }
    }

    /**
     * 生成父订单号
     *
     * @return
     */
    private String createParentOrderNo() {
        String time = String.valueOf(System.currentTimeMillis());
        String key = order_no_key + time;
        String orderNo = "PX" + time + redisService.incr(key, 1L, TimeUnit.SECONDS);
        return orderNo;
    }

    /**
     * 生成子订单号
     *
     * @return
     */
    private String createOrderNo() {
        String time = String.valueOf(System.currentTimeMillis());
        String key = order_no_key + time;
        String orderNo = "YX" + time + redisService.incr(key, 1L, TimeUnit.SECONDS);
        return orderNo;
    }

    /**
     * 生成充值订单号
     */
    private String createRechargeOrderNo() {
        String time = String.valueOf(System.currentTimeMillis());
        String key = order_no_key + time;
        String orderNo = "RX" + time + redisService.incr(key, 1L, TimeUnit.SECONDS);
        return orderNo;
    }


    /**
     * 创建子订单，如果有多个供应商的订单，需要拆单
     *
     * @param settle
     * @param parent
     */
    private void createChildOrder(OrderSettlementVo settle, OrderInfoParent parent) {
        parent.setOrderInfoList(new ArrayList<>());
        logger.info("=================开始创建子订单===================");
        OrderSettleTotalVo totalVo = new OrderSettleTotalVo();
        totalVo.setBalance(parent.getPayByBalance());
        totalVo.setCouponAmount(parent.getUseCouponAmount());
        totalVo.setCouponRate(settle.getCouponRate());
        totalVo.setDiscountAmount(parent.getDiscountAmount());
        totalVo.setDiscountRate(parent.getDiscountRate());
        totalVo.setRedBag(parent.getPayByRedBag());
        totalVo.setScore(parent.getPayByScore());
        totalVo.setFreightAmount(parent.getFreightAmount());

        //保存非供应商子订单
        createChildOrder(settle, parent, totalVo, null, null);
    }


    /**
     * 保存子订单
     *
     * @param settle
     * @param parent
     * @param totalVo
     * @param carts
     * @param supplierId
     */
    private void createChildOrder(OrderSettlementVo settle, OrderInfoParent parent, OrderSettleTotalVo totalVo, List<OrderShopCart> carts, Long supplierId) {

        //商品总额
        Long amount = 0L;
        //现金付款
        Long payAmount = 0L;
        //会员折扣
        Long discountAmount = 0L;
        //优惠券支付
        Long couponAmount = 0L;
        //积分支付
        Long score = 0L;
        //余额支付
        Long balance = 0L;
        //红包支付
        Long redBag = 0L;

        //订单邮费
        Long freightAmount = 0L;

        CustomerInfo customerInfo = iCustomerInfoService.getById(SecurityUtils.getCustomerUid());
        if (customerInfo == null){
            throw new RuntimeException("没有找到用户信息");
        }


        //供应商名称
        String supplierName = null;

        List<OrderInfoItem> items = new ArrayList<OrderInfoItem>();
        OrderInfoItem item = null;
        String isDdl = "0";
        ProductInfo pi = settle.getProductInfo();

            item = new OrderInfoItem();
            item.setOrderUid(null);

            item.setDataStatus(DataStatus.valid.getKey());
            item.setItemNumber(pi.getNumbers().longValue());
            item.setPrice(0L);
            item.setItemAmount(0L);
            item.setOrderType(pi.getOrderType());
            item.setCustomerUid(SecurityUtils.getCustomerUid());
            //初始化优惠金额
            item.setDiscountAmount(0L);
            item.setPayByBalance(0L);
            item.setPayByRedBag(0L);
            item.setUseCouponAmount(0L);
            item.setPayDate(new Date());
            item.setPayStatus("1");
            if (pi.getOrderType().equals("good")){
                item.setCostPrice(0L);
                item.setPayByScore(pi.getJifen().longValue());
                score += item.getPayByScore();
            }else if (pi.getOrderType().equals("maiduan")){
                item.setCostPrice(pi.getCostPrice().longValue());
                item.setPayByScore(0L);
                score += item.getCostPrice();
            }else{
                item.setCostPrice(0L);
                item.setPayByScore(0L);
            }

            item.setPayAmount(0L);
            //只有非活动商品才参与折扣、优惠券等计算

            item.setProName(pi.getProductName());
            item.setProUid(pi.getProductUid());
            item.setProNo(pi.getProductNo());
            if (StringUtils.isNotEmpty(pi.getDownloadFile())) {
                item.setProUnit(pi.getDownloadFile().substring(pi.getDownloadFile().lastIndexOf(".")+1));
            }
            //item.setImgUrl(cart.getProImgUrl());
            item.setSaleStatus(SaleStatusEnum.normal.getKey());
            item.setSettlementStatus(SettlementEnum.unSettlement.getKey());
            item.setSettlementTime(null);
            item.setSkuDesc(pi.getLunwenType());

            item.setCreateTime(parent.getCreateTime());
            item.setCreateUid(SecurityUtils.getCustomerUid());
            item.setUpdateTime(parent.getCreateTime());
            item.setUpdateUid(item.getCreateUid());
            items.add(item);


        /**
         * 保存订单信息
         */
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setAddressUid(settle.getAddressId());
        //orderInfo.setDeliverMethod(settle.getShipMethod());
        orderInfo.setAutoReceiveTime(null);
        orderInfo.setBuyMes(settle.getBuyerMsg());
        orderInfo.setCancelTime(null);
        orderInfo.setOrderTitle("用户网站下单");
        orderInfo.setCommentStatus(CommentStatusEnum.unComment.getKey());
        orderInfo.setCreateTime(parent.getCreateTime());
        orderInfo.setCurrencyUnit("RMB");
        orderInfo.setCustomerName(customerInfo.getCustomerName());
        orderInfo.setPhone(customerInfo.getPhone());
        orderInfo.setCustomerUid(SecurityUtils.getCustomerUid());
        orderInfo.setDeliverMethod(settle.getDeliverMethod());
        orderInfo.setDiscountRate(parent.getDiscountRate());
        orderInfo.setDiscountAmount(discountAmount);
        orderInfo.setFreightAmount(freightAmount);
        orderInfo.setSupplierName(customerInfo.getCustomerNo());
        orderInfo.setExpireDate(parent.getExpireDate());
        orderInfo.setInvoiceStatus(InvoiceStatusEnum.unInvoice.getKey());
        orderInfo.setInvoiceUid(settle.getInvoiceId());
        orderInfo.setIp(SecurityUtils.getCustomerClientIp());
        orderInfo.setOrderAmount(amount);
        orderInfo.setOrderNo(createOrderNo());
        orderInfo.setOrderPackStatus(PackStatusEnum.collect.getKey());
        orderInfo.setOrderStatus(OrderStatusEnum.effect.getKey());
        orderInfo.setOrderType(pi.getOrderType());
        orderInfo.setPayAmount(payAmount);
        orderInfo.setPayByBalance(balance);
        orderInfo.setPayMethod(settle.getPayMethod());
        orderInfo.setPayByRedBag(redBag);
        orderInfo.setPayStatus(PayStatusEnum.unpaid.getKey());
        orderInfo.setParentOrderNo(parent.getParentOrderNo());
        orderInfo.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
        orderInfo.setPlatSource(SecurityUtils.getCustomerSourcePort());
        orderInfo.setSendStatus(SendStatusEnum.unShip.getKey());
        orderInfo.setSupplierUid(supplierId);
        //orderInfo.setSupplierName(supplierName);
        orderInfo.setUseCouponAmount(couponAmount);
        orderInfo.setPayByScore(score);
        orderInfo.setUseCouponUid(parent.getUseCouponUid());
        orderInfo.setUpdateTime(parent.getCreateTime());
        orderInfo.setUpdateUser(orderInfo.getCustomerUid());
        orderInfo.setUpdateUserName(SecurityUtils.getCustomerUserName());
        orderInfo.setStoreId(settle.getStoreId());
        orderInfo.setIsDdl(isDdl);
        if (this.save(orderInfo)) {
            for (OrderInfoItem i : items) {
                i.setOrderUid(orderInfo.getOrderUid());
            }
            if (itemService.saveBatch(items)) {
            }
        }
    }

    /**
     * 保存子订单
     *
     * @param settle
     * @param parent
     * @param totalVo
     * @param carts
     */
    private void updateChildOrder(OrderSettlementVo settle, OrderInfoParent parent, OrderSettleTotalVo totalVo, List<OrderInfoItem> carts, OrderInfo orderInfo) {
        logger.info("\n==========保存子订单参数：{}=========", JSON.toJSONString(carts));
        if (carts.size() < 1) {
            return;
        }

        //商品总额
        Long amount = 0L;
        //现金付款
        Long payAmount = 0L;
        //会员折扣
        Long discountAmount = 0L;
        //优惠券支付
        Long couponAmount = 0L;
        //积分支付
        Long score = 0L;
        //余额支付
        Long balance = 0L;
        //红包支付
        Long redBag = 0L;

        //订单邮费
        Long freightAmount = 0L;
        totalVo.setFreightAmount(freightAmount);

        Long couponRate = 0L;
        if (parent.getUseCouponAmount()>0L){
            Long money = 0L;
            for (OrderInfoItem cart : carts) {
                if (cart.isUseCoupon()){
                    money += cart.getItemAmount();
                }
            }
            if (money>0L) {
                Long coupon = parent.getUseCouponAmount() * 100;
                couponRate = coupon / money;
                if (couponRate>0 && (coupon % money)>0) {
                    couponRate +=1L;
                }
                if (couponRate > 100L) {
                    couponRate = 100L;
                }
                if (couponRate < 0L) {
                    couponRate = 0L;
                }
            }
        }

        for (OrderInfoItem item : carts) {
            amount += item.getItemAmount();

            //初始化优惠金额
            item.setDiscountAmount(0L);
            item.setPayByBalance(0L);
            item.setPayByRedBag(0L);
            item.setUseCouponAmount(0L);
            item.setPayByScore(0L);
            item.setPayAmount(item.getItemAmount());

            //只有非活动商品才参与折扣、优惠券等计算
            //if (StringUtils.isEmpty(cart.getActivityType())) {
            //计算身份折扣
            if (item.isUseMemberDiscount()) {
                if (parent.getDiscountRate() > 0 && parent.getDiscountRate() < 100 && totalVo.getDiscountAmount() > 0) {
                    item.setDiscountAmount(item.getItemAmount() * (100 - parent.getDiscountRate()) / 100);
                    //当总的优惠金额不足时，为了避免产生负数，做一下判断
                    if (totalVo.getDiscountAmount() - item.getDiscountAmount() < 0) {
                        item.setDiscountAmount(totalVo.getDiscountAmount());
                    }
                    totalVo.setDiscountAmount(totalVo.getDiscountAmount() - item.getDiscountAmount());
                    item.setPayAmount(item.getPayAmount()-item.getDiscountAmount());
                    discountAmount += item.getDiscountAmount();
                }
            }
            if (item.isUseCoupon()) {
                //优惠券支付
                if (parent.getUseCouponAmount() > 0 && totalVo.getCouponAmount() > 0) {
                    if (totalVo.getCouponRate()>0){
                        item.setUseCouponAmount(item.getItemAmount() * (100 - totalVo.getCouponRate()) / 100);
                    }else{
                        /*
                        if (item.getItemAmount()<=totalVo.getCouponAmount()){
                            item.setUseCouponAmount(item.getItemAmount());
                        }else{
                            item.setUseCouponAmount(totalVo.getCouponAmount());
                        }*/
                        item.setUseCouponAmount(item.getItemAmount()*couponRate/100);

                    }
                    if (totalVo.getCouponAmount() - item.getUseCouponAmount() < 0) {
                        item.setUseCouponAmount(totalVo.getCouponAmount());
                    }
                    item.setPayAmount(item.getPayAmount()-item.getUseCouponAmount());
                    totalVo.setCouponAmount(totalVo.getCouponAmount() - item.getUseCouponAmount());
                    couponAmount += item.getUseCouponAmount();
                }
            }

            //积分支付
            if (parent.getPayByScore() > 0 && item.getPayByScore() > 0 && totalVo.getScore() > 0) {
                //item.setPayByScore(cart.getTotalScore());
                if (totalVo.getScore() - item.getPayByScore() < 0) {
                    item.setPayByScore(totalVo.getScore());
                }
                totalVo.setScore(totalVo.getScore() - item.getPayByScore());
                score += item.getPayByScore();
            }

            //银币支付
            if (parent.getPayByRedBag() > 0 && totalVo.getRedBag() > 0 && item.isUseBoluosilverCoin() && item.getPayAmount()>0) {
                //item.setPayByRedBag(item.getItemAmount());
                item.setPayByRedBag(item.getPayAmount());
                if (totalVo.getRedBag() - item.getPayByRedBag() < 0) {
                    item.setPayByRedBag(totalVo.getRedBag());
                }
                item.setPayAmount(item.getPayAmount()-item.getPayByRedBag());
                totalVo.setRedBag(totalVo.getRedBag() - item.getPayByRedBag());
                redBag += item.getPayByRedBag();
            }

            //计算金币抵扣
            if (parent.getPayByBalance() > 0 && totalVo.getBalance() > 0 && item.isUseBoluoGoldCoin() && item.getPayAmount()>0) {
                //item.setPayByBalance(item.getItemAmount());
                item.setPayByBalance(item.getPayAmount());
                if (totalVo.getBalance() - item.getPayByBalance() < 0) {
                    item.setPayByBalance(totalVo.getBalance());
                }
                item.setPayAmount(item.getPayAmount()-item.getPayByBalance());
                totalVo.setBalance(totalVo.getBalance() - item.getPayByBalance());
                balance += item.getPayByBalance();
            }


            if (item.getPayAmount()<0L) {
                item.setPayAmount(0L);
            }
            payAmount += item.getPayAmount();
            item.setSaleStatus(SaleStatusEnum.normal.getKey());
            item.setSettlementStatus(SettlementEnum.unSettlement.getKey());
            item.setSettlementTime(null);

        }

        /**
         * 保存订单信息
         */


        orderInfo.setCommentStatus(CommentStatusEnum.unComment.getKey());
        orderInfo.setCurrencyUnit("RMB");
        orderInfo.setDeliverMethod(settle.getDeliverMethod());
        orderInfo.setDiscountRate(parent.getDiscountRate());
        orderInfo.setDiscountAmount(discountAmount);
        orderInfo.setFreightAmount(freightAmount);
        orderInfo.setInvoiceStatus(InvoiceStatusEnum.unInvoice.getKey());
        orderInfo.setIp(SecurityUtils.getCustomerClientIp());
        orderInfo.setOrderAmount(amount);
        orderInfo.setOrderPackStatus(PackStatusEnum.collect.getKey());
        orderInfo.setOrderStatus(OrderStatusEnum.effect.getKey());
        orderInfo.setOrderType(OrderTypeEnum.good.getKey());
        orderInfo.setPayAmount(payAmount);
        orderInfo.setPayByBalance(balance);
        orderInfo.setPayMethod(settle.getPayMethod());
        orderInfo.setPayByRedBag(redBag);
        orderInfo.setPayStatus(PayStatusEnum.unpaid.getKey());
        orderInfo.setSendStatus(SendStatusEnum.unShip.getKey());
        orderInfo.setUseCouponAmount(couponAmount);
        orderInfo.setPayByScore(score);
        orderInfo.setUseCouponUid(parent.getUseCouponUid());
        orderInfo.setUpdateTime(parent.getCreateTime());
        orderInfo.setUpdateUser(orderInfo.getCustomerUid());
        orderInfo.setUpdateUserName(SecurityUtils.getCustomerUserName());
        orderInfo.setParentOrderNo(parent.getParentOrderNo());
        orderInfo.setIsDdl("0");
        parent.setPayByBalance(balance);
        if (this.updateById(orderInfo)) {
            if (itemService.saveOrUpdateBatch(carts)) {
                List<OrderInfoItemPay> pays = new ArrayList<>();
                List<BalanceItemVo> balanceDetail = settle.getBalanceDetail();
                Map<Long, BalanceItemVo> fundMap = new HashMap<>();
                for (OrderInfoItem i : carts) {
                    if (i.getPayByBalance() > 0 || i.getPayByRedBag() > 0) {
                        if (i.getPayByRedBag() > 0) {
                            OrderInfoItemPay pay = new OrderInfoItemPay();
                            pay.setPayGoldCoin(0L);
                            pay.setPaySilverCoin(i.getPayByRedBag());
                            pay.setPayStoreId(orderInfo.getStoreId());
                            pay.setCreateName(SecurityUtils.getCustomerUserName());
                            pay.setCreateTime(i.getCreateTime());
                            pay.setCreateUser(SecurityUtils.getCustomerUid());
                            pay.setDataStatus(DataStatus.valid.getKey());
                            pay.setItemId(i.getItemUid());
                            pay.setOrderId(i.getOrderUid());
                            pay.setUpdateUser(pay.getCreateUser());
                            pay.setUpdateTime(pay.getCreateTime());
                            pay.setUpdateName(pay.getCreateName());
                            pay.setPayStoreId(i.getStoreId());
                            pays.add(pay);
                        }
                        if (i.getPayByBalance() > 0) {
                            Long sumBalance = 0L;
                            for (BalanceItemVo vo : balanceDetail) {
                                if (vo.getBalance() >= i.getPayByBalance() - sumBalance) {
                                    OrderInfoItemPay pay = new OrderInfoItemPay();
                                    pay.setPayGoldCoin(i.getPayByBalance() - sumBalance);
                                    pay.setPaySilverCoin(0L);
                                    pay.setPayStoreId(vo.getStoreId());
                                    pay.setCreateName(SecurityUtils.getCustomerUserName());
                                    pay.setCreateTime(i.getCreateTime());
                                    pay.setCreateUser(SecurityUtils.getCustomerUid());
                                    pay.setDataStatus(DataStatus.valid.getKey());
                                    pay.setItemId(i.getItemUid());
                                    pay.setOrderId(i.getOrderUid());
                                    pay.setUpdateUser(pay.getCreateUser());
                                    pay.setUpdateTime(pay.getCreateTime());
                                    pay.setUpdateName(pay.getCreateName());
                                    vo.setBalance(vo.getBalance() - pay.getPayGoldCoin());
                                    sumBalance += pay.getPayGoldCoin();
                                    pays.add(pay);
                                } else {
                                    OrderInfoItemPay pay = new OrderInfoItemPay();
                                    pay.setPayGoldCoin(vo.getBalance());
                                    pay.setPaySilverCoin(0L);
                                    pay.setPayStoreId(vo.getStoreId());
                                    pay.setCreateName(SecurityUtils.getCustomerUserName());
                                    pay.setCreateTime(i.getCreateTime());
                                    pay.setCreateUser(SecurityUtils.getCustomerUid());
                                    pay.setDataStatus(DataStatus.valid.getKey());
                                    pay.setItemId(i.getItemUid());
                                    pay.setOrderId(i.getOrderUid());
                                    pay.setUpdateUser(pay.getCreateUser());
                                    pay.setUpdateTime(pay.getCreateTime());
                                    pay.setUpdateName(pay.getCreateName());
                                    vo.setBalance(vo.getBalance() - pay.getPayGoldCoin());
                                    sumBalance += pay.getPayGoldCoin();
                                    pays.add(pay);
                                }
                                if (sumBalance >= i.getPayByBalance()) {
                                    break;
                                }
                            }
                        }
                    }
                }
                if (pays.size() > 0) {
                    orderInfoItemPayService.saveBatch(pays);
                }
            }
        }
    }


    /**
     * 创建父订单
     *
     * @param settle
     * @return
     */
    private OrderInfoParent createParentOrder(OrderSettlementVo settle) {
        logger.info("=================开始创建支付订单===================");
        //商品总额
        Long parentAmount = settle.getShopAmount();
        Long score = settle.getScoreAmount();

        if (settle.getFreight() == null) {
            settle.setFreight(0L);
        }
        if (settle.getRedBag() == null) {
            settle.setRedBag(0L);
        }
        if (settle.getBalance() == null) {
            settle.setBalance(0L);
        }
        if (settle.getScore() == null) {
            settle.setScore(0L);
        }
        if (settle.getDiscountAmount() == null) {
            settle.setDiscountAmount(0L);
            settle.setDiscountRate(0L);
        }
        if (settle.getCouponAmount() == null) {
            settle.setCouponAmount(0L);
            settle.setCouponRate(0L);
        }


        //现金支付金额
//        Long payAmount = parentAmount+settle.getFreight()-settle.getBalance()-settle.getRedBag()-settle.getDiscountAmount()-settle.getCouponAmount();
        //Long payAmount = parentAmount + settle.getFreight() - settle.getBalance() - settle.getRedBag() - settle.getDiscountAmount() - settle.getCouponAmount();
        Long payAmount = parentAmount;

        if (payAmount <= 0L){
            payAmount = 0L;
            settle.setBalance(0L);
            settle.setRedBag(0L);
        }

        if (payAmount > 0L && settle.getRedBag()>0L){
            Long tmp = payAmount - settle.getRedBag();
            if (tmp <= 0L){
                settle.setRedBag(payAmount);
                settle.setBalance(0L);
                payAmount = 0L;
            }else{
                payAmount = tmp;
                if (settle.getBalance()>tmp)
                    settle.setBalance(tmp);
            }
        }

        if (payAmount > 0L && settle.getBalance()>0L){
            Long tmp = payAmount - settle.getBalance();
            if (tmp <= 0L){
                settle.setBalance(payAmount);
                payAmount = 0L;
            }else{
                payAmount = tmp;
            }
        }

        OrderInfoParent parent = new OrderInfoParent();
        parent.setIsRecharge(settle.getIsRecharge());
        parent.setOrderType(settle.getOrderType());
        parent.setCreateTime(new Date());
        parent.setDiscountAmount(settle.getDiscountAmount());
        parent.setDiscountRate(settle.getDiscountRate());
        parent.setParentAmount(parentAmount);
        parent.setParentOrderNo(createParentOrderNo());
        parent.setPayAmount(payAmount);
        parent.setPayByScore(score);
        parent.setPayByBalance(settle.getBalance());
        //parent.setPayByScore(settle.getScore());
        parent.setFreightAmount(settle.getFreight());
        parent.setPayByRedBag(settle.getRedBag());
        parent.setPayMethod(settle.getPayMethod());
        parent.setPayStatus(PayStatusEnum.unpaid.getKey());
        parent.setExpireDate(settle.getExpireDate());
        parent.setUseCouponUid(settle.getCouponId());
        parent.setUseCouponAmount(settle.getCouponAmount());
        parent.setProfitSharing(ProfitSharingEnum.Y.toString());
        parent.setCustomerId(SecurityUtils.getCustomerUid());
        parent.setPlatformId(SecurityUtils.getCustomerPlatformUid());
        parent.setStoreId(settle.getStoreId());
        if (orderInfoParentService.save(parent)) {
            return parent;
        }
        throw new BaseException("创建订单失败，请稍后再试");
    }


    /**
     * 创建兑换码订单
     *
     * @param settle
     * @return
     */
    private OrderInfoParent createExchangeParentOrder(OrderSettlementVo settle) {
        logger.info("=================开始创建支付订单===================");
        //商品总额
        Long parentAmount = 0L;
        Long score = 0L;
        if (settle.getFreight() == null) {
            settle.setFreight(0L);
        }
        if (settle.getRedBag() == null) {
            settle.setRedBag(0L);
        }
        if (settle.getBalance() == null) {
            settle.setBalance(0L);
        }
        if (settle.getScore() == null) {
            settle.setScore(0L);
        }
        if (settle.getDiscountAmount() == null) {
            settle.setDiscountAmount(0L);
            settle.setDiscountRate(0L);
        }
        if (settle.getCouponAmount() == null) {
            settle.setCouponAmount(0L);
            settle.setCouponRate(0L);
        }

        Long payAmount = 0L;
        OrderInfoParent parent = new OrderInfoParent();
        parent.setIsRecharge(settle.getIsRecharge());
        parent.setCreateTime(new Date());
        parent.setDiscountAmount(settle.getDiscountAmount());
        parent.setDiscountRate(settle.getDiscountRate());
        parent.setParentAmount(parentAmount);
        parent.setParentOrderNo(createParentOrderNo());
        parent.setPayAmount(payAmount);
        parent.setPayByScore(score);
        parent.setPayByBalance(settle.getBalance());
        //parent.setPayByScore(settle.getScore());
        parent.setFreightAmount(settle.getFreight());
        parent.setPayByRedBag(settle.getRedBag());
        parent.setPayMethod(PayMethodEnum.exchange.getKey());
        parent.setPayStatus(PayStatusEnum.paid.getKey());
        parent.setPayTime(new Date());
        parent.setExpireDate(settle.getExpireDate());
        parent.setUseCouponUid(settle.getCouponId());
        parent.setUseCouponAmount(settle.getCouponAmount());
        parent.setProfitSharing(ProfitSharingEnum.N.toString());
        parent.setCustomerId(SecurityUtils.getCustomerUid());
        parent.setPlatformId(SecurityUtils.getCustomerPlatformUid());
        if (orderInfoParentService.save(parent)) {
            return parent;
        }
        throw new BaseException("创建订单失败，请稍后再试");
    }

    /**
     * 检验购物车商品价格、库存、状态等信息是否和购物车数据一致，如果不一致，不能结算
     */
    private Long checkProductInfo(List<OrderShopCart> carts,CouponInfoDetailVo coupon) {
        //获取店铺设置的支付时间，并与活动时间比较，取最小的时间为支付时长
        Long payMinute = 30L;

        for (OrderShopCart cart : carts) {
            if (cart.getActivityUid() != null && cart.getActivityProUid() != null) {
                //判断是否为活动产品
                payMinute = checkSaleShopping(cart);
            } else if (cart.getActivityUid() != null) {
                //判断是否为活动(套餐活动)
                payMinute = checkActivityShopping(cart);
            } else {
                //没有搞活动
                checkNormalShopping(cart,coupon);
            }
        }
        if (payMinute == null) {
            payMinute = 30L;
        }
        PlatformGeneralsettingsVo data = platformGeneralsettingsService.get(SecurityUtils.getCustomerPlatformUid());
        if (ObjectUtil.isNotEmpty(data)) {
            if (payMinute > Long.parseLong(data.getWaitOrderPayment()))
                payMinute = Long.parseLong(data.getWaitOrderPayment());
        }
        return payMinute;
    }

    /**
     * 判断营销活动的商品，除套餐以外，搞活动的商品不再享受会员折扣和优惠券抵扣
     *
     * @param cart
     */
    private Long checkSaleShopping(OrderShopCart cart) {

        return 5L;
    }

    /**
     * 判断营销活动套餐的数据
     *
     * @param cart
     */
    private Long checkActivityShopping(OrderShopCart cart) {

        return 5L;
    }

    /**
     * 判断没有搞活动的商品，从商品基础库里查询数据做判断
     * 尚未加入会员折扣信息的计算，后续需要加入会员身份的折扣结算
     *
     * @param cart
     */
    private void checkNormalShopping(OrderShopCart cart,CouponInfoDetailVo coupon) {
        if (cart.getIsDdl().equals(DataStatus.valid.getKey())) {

        }else if (cart.getProType().equals(CardServiceTypeEnum.product.getKey())) {
            ProductInfoVo p = iProductInfoService.getProductDetail(cart.getProUid());
            if (p != null) {
                if (!DataStatus.valid.getKey().equals(p.getDataStatus())) {
                    throw new BaseException("商品未上架，不能结算");
                }
                if (!DataStatus.valid.getKey().equals(p.getAuditStatus())) {
                    throw new BaseException("商品未上架，不能结算");
                }
                cart.setUseBoluoGoldCoin(DataStatus.valid.getKey().equals(p.getIsUseBoluoGoldCoin()));
                cart.setUseBoluosilverCoin(DataStatus.valid.getKey().equals(p.getIsUseBoluoSilverCoin()));
                cart.setUseCoupon(DataStatus.valid.getKey().equals(p.getIsUseCoupon()));
                cart.setUseMemberDiscount(DataStatus.valid.getKey().equals(p.getIsUseMemberDiscount()));
                cart.setDiscountMemberLevel(p.getMemberLevel());
                if (cart.getSkuUid() != null) {
                    //如果是SKU，则判断SKU的信息
                    SkuApi sku = iProductInfoService.getSkuDetail(cart.getSkuUid());
                    if (!DataStatus.valid.getKey().equals(sku.getSkuStatus())) {
                        throw new BaseException(p.getProductName() + "【" + cart.getSkuDesc() + "】已下架，不能结算");
                    }
                    if (sku.getStockNumber() < cart.getCartNumber()) {
                        throw new BaseException(p.getProductName() + "【" + cart.getSkuDesc() + "】库存不足，不能结算");
                    }
                    if (sku.getSkuRetailPrice().longValue() != cart.getPrice()) {
                        throw new BaseException(p.getProductName() + "【" + cart.getSkuDesc() + "】已变价，不能结算");
                    }
                } else {
                    //判断商品的信息
                    if (p.getStockNumber() < cart.getCartNumber()) {
                        throw new BaseException(p.getProductName() + "库存不足，不能结算");
                    }
                    if (p.getRetailPrice().longValue() != cart.getPrice()) {
                        throw new BaseException(p.getProductName() + "已变价，不能结算");
                    }
                }
                resetUseCoupon(cart,CardServiceTypeEnum.product.getKey(),coupon);
            } else {
                throw new BaseException("没有找到商品信息");
            }
        } else if (cart.getProType().equals(CardServiceTypeEnum.serviceItem.getKey())) {

        } else if (cart.getProType().equals(CardServiceTypeEnum.card.getKey())) {

        }else if (cart.getProType().equals(CardServiceTypeEnum.coupon.getKey())){

        }
    }

    /**
     * 检验余额，积分或红包是否足够
     *
     * @param settle
     */
    private CustomerFundVo checkBalanceAndRedBagAndScore(OrderSettlementVo settle) throws Exception {
        CustomerFundVo rst = null;
        CustomerFund fund = iCustomerFundService.getByCustomerId(settle.getCustomerId());
        if (ObjectUtil.isEmpty(fund)) {
            throw new BaseException("没有找到会员钱包信息");
        }
        rst = new CustomerFundVo();
        BeanUtils.copyProperties(fund, rst);
        logger.info("\n==========查询用户资金信息parameter:{}==========\n===========result:{}===========\n",
                settle.getCustomerId(), JSONObject.toJSONString(rst));

        if (settle.getBalance() != null && settle.getBalance() > 0) {
            //settle.setBalance(settle.getBalance()*100);
            if (settle.getBalance() > settle.getCanUseGoldCionAmount()) {
                settle.setBalance(settle.getCanUseGoldCionAmount());
            }
            if (settle.getBalance() > rst.getBalance()) {
                throw new BaseException("金币不足" + MoneyUtils.changeF2Y(settle.getBalance()) + "元，不能结算");
            }
        }
        rst.setRedBag(0L);
        CustomerFundStore fundStore = customerFundStoreService.selectCustomerFund(settle.getStoreId(), settle.getCustomerId());
        if (fundStore != null) {
            rst.setRedBag(fundStore.getRedBag());
        }
        if (settle.getRedBag() != null && settle.getRedBag() > 0) {
            if (fundStore == null || fundStore.getRedBag() < settle.getRedBag()) {
                throw new BaseException("银币不足" + MoneyUtils.changeF2Y(settle.getRedBag()) + "元，不能结算");
            }
            if (settle.getRedBag() > settle.getCanUseSilverCionAmount()) {
                settle.setRedBag(settle.getCanUseSilverCionAmount());
            }
        }
        if (settle.getScoreAmount() != null && settle.getScoreAmount() > 0) {
            if (settle.getScoreAmount() > rst.getScore()) {
                throw new BaseException("菠萝派不足" + settle.getScoreAmount() + "分，不能结算");
            }
        }
        return rst;
    }

    /**
     * 活动用户信息
     *
     * @param settle
     */
    private void getUserInfo(OrderSettlementVo settle) {
        settle.setDiscountAmount(0L);
        settle.setDiscountRate(0L);
        CustomerVo customerVo = iCustomerInfoService.getNewCustomerVo(settle.getCustomerId());

        if (ObjectUtil.isEmpty(customerVo)) {
            throw new BaseException("没有找到用户信息");
        }
        settle.setMemberGrade(customerVo.getMemberGrade().longValue());
        logger.info("\n==========获取用户信息,折扣比例parameter:{}==========\n===========result:{}===========\n",
                settle.getCustomerId(), JSONObject.toJSONString(customerVo));

        settle.setCustomerInfo(customerVo);
        List<LevelAndPrivilege> list = customerVo.getLevelPrivilegeList();
        if (list == null || list.size() == 0) {
            return;
        }
        for (LevelAndPrivilege cp : list) {
            if (CustomerLevelPrivilegeEnum.freeShipping.getKey().equals(cp.getPrivilegeName())) {
                settle.setFreeFreight(Boolean.TRUE);
                settle.setFreight(0L);
                //break;
            } else if (CustomerLevelPrivilegeEnum.discount.getKey().equals(cp.getPrivilegeName())) {
                //权益折扣，非百分制，这里做转换
                logger.info("\n==========用户折扣值：{}=============\n", cp.getPrivilegeValue());
                settle.setMemberDiscount(true);
                settle.setDiscountRate(new BigDecimal(cp.getPrivilegeValue()).multiply(new BigDecimal(10)).longValue());
                /*
                Long amount = settle.getNormalShopAmount();
                if (amount != null && amount > 0L) {
                    settle.setDiscountAmount(amount * (100 - settle.getDiscountRate()) / 100);
                } else {
                    settle.setDiscountAmount(0L);
                }*/
            }
        }
        logger.info("\n==========折扣比例：{}，折扣金额：{}=========", settle.getDiscountRate(), settle.getDiscountAmount());
    }


    /**
     * 检验优惠券是否能用
     *
     * @param settle
     */
    private void checkCoupon(OrderSettlementVo settle) {

    }

    /**
     * 坚持运费
     *
     * @param settle
     * @param addressVo
     * @param amount
     */
    private void checkFreight(OrderSettlementVo settle, CustomerAddressVo addressVo, Long amount) {
        PlatformFreightVo vo = new PlatformFreightVo();
        vo.setFreightProvince(addressVo.getProvinceName());
        vo.setPlatformUid(settle.getPlatformId());
        PlatformFreightVo freightVo = iPlatformFreightService.getFreight(vo);
        if (ObjectUtil.isEmpty(freightVo)) {
            throw new BaseException("缺少该地区运费信息配置");
        }
        if (freightVo.getMoudleAmount().longValue() <= amount) {
            settle.setFreeFreight(Boolean.TRUE);
            settle.setFreight(0L);
        } else {
            settle.setFreight(freightVo.getFreightInitFate().longValue());
        }
        if (FreightTypeEnum.aloeGel.getKey().equals(freightVo.getFreightType())) {
            settle.setFreight(freightVo.getFreightInitFate().longValue());
        } else if (FreightTypeEnum.noDelivery.getKey().equals(freightVo.getFreightType())) {
            throw new BaseException("该地区暂不支持配送");
        }
        logger.info("\n=====是否包邮：{}，邮费金额：{}======", settle.getFreeFreight(), settle.getFreight());
    }

    /**
     * 检验收货地址
     *
     * @param settle
     */
    private CustomerAddressVo checkAddress(OrderSettlementVo settle) {
        CustomerAddressVo vo = null;
        CustomerAddress byId = iCustomerAddressService.getById(settle.getAddressId());
        if (ObjectUtil.isEmpty(byId)) {
            throw new BaseException("没有找到地址信息");
        }
        vo = new CustomerAddressVo();
        BeanUtils.copyProperties(byId, vo);
        if (vo.getCustomerUid().longValue() != settle.getCustomerId()) {
            throw new BaseException("没有找到地址信息");
        }
        return vo;
    }

    /**
     * 我的订单列表
     *
     * @param query
     * @return
     */
    @Override
    public List<OrderInfoVo> selectOrder(OrderQuery query) {
        List<OrderInfoVo> voList = getOrderInfoVos(query);

        return voList;
    }

    @Nullable
    private List<OrderInfoVo> getOrderInfoVos(OrderQuery query) {
        logger.info("\n==========我的订单列表查询参数：{}============", JSON.toJSONString(query));
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(query, orderInfo);

        queryStatus(orderInfo);

        QueryWrapper<OrderInfo> queryWrapper = Wrappers.query();
        queryWrapper.eq("CUSTOMER_UID", orderInfo.getCustomerUid());
        queryWrapper.eq("ORDER_STATUS", OrderStatusEnum.effect.getKey());

        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getPayStatus())) && orderInfo.getPayStatus() != null) {
            queryWrapper.eq("PAY_STATUS", orderInfo.getPayStatus());
            if (PayStatusEnum.unpaid.getKey().equals(orderInfo.getPayStatus()))
                queryWrapper.ne("ORDER_TYPE", ActivityTypeEnum.bargain.getKey());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getPayMethod())) && orderInfo.getPayMethod() != null) {
            queryWrapper.eq("PAY_METHOD", orderInfo.getPayMethod());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getPlatSource())) && orderInfo.getPlatSource() != null) {
            queryWrapper.eq("PLAT_SOURCE", orderInfo.getPlatSource());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getInvoiceStatus())) && orderInfo.getInvoiceStatus() != null) {
            queryWrapper.eq("INVOICE_STATUS", orderInfo.getInvoiceStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getDeliverMethod())) && orderInfo.getDeliverMethod() != null) {
            queryWrapper.eq("DELIVER_METHOD", orderInfo.getDeliverMethod());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getSendStatus())) && orderInfo.getSendStatus() != null) {
            queryWrapper.eq("SEND_STATUS", orderInfo.getSendStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getOrderPackStatus())) && orderInfo.getOrderPackStatus() != null) {
            queryWrapper.eq("ORDER_PACK_STATUS", orderInfo.getOrderPackStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderInfo.getCommentStatus())) && orderInfo.getCommentStatus() != null) {
            queryWrapper.eq("COMMENT_STATUS", orderInfo.getCommentStatus());
        }

        queryWrapper.orderByDesc("CREATE_TIME");
        List<OrderInfoVo> voList = new ArrayList<>();

        List<OrderInfo> orderInfoList = orderInfoMapper.selectList(queryWrapper);
        if (ObjectUtil.isNotEmpty(orderInfoList)) {
            logger.info("\n==========我的订单列表：{}============", JSON.toJSONString(orderInfoList));
            boolean flag = true;
            OrderInfoVo vo = null;
            List<OrderItemVo> itemVoList = null;

            PlatformGeneralsettingsVo data = platformGeneralsettingsService.get(query.getPlatformUid());
            for (OrderInfo order : orderInfoList) {
                flag = true;
                query.setOrderUid(order.getOrderUid());
                itemVoList = itemService.getByOrderUidAndProName(query);
                if (ObjectUtil.isNotEmpty(query.getProName()) && ObjectUtil.isEmpty(itemVoList)) {
                    flag = false;
                }

                if (flag) {
                    vo = new OrderInfoVo();
                    BeanUtils.copyProperties(order, vo);
                    /*
                    //判断已支付订单是否超出可取消时间
                    if (PayStatusEnum.paid.getKey().equals(order.getPayStatus()) && SendStatusEnum.unShip.getKey().equals(order.getSendStatus())) {
                        Date expire = DateUtils.add(order.getPayTime(), Long.parseLong(data.getOrderPayment()));
                        if (System.currentTimeMillis() > expire.getTime())
                            vo.setShowCancelFlag(Boolean.TRUE);
                        else
                            vo.setShowCancelFlag(Boolean.FALSE);
                    }*/
                    if (PayStatusEnum.paid.getKey().equals(order.getPayStatus())) {
                        vo.setShowCancelFlag(Boolean.FALSE);
                    }else{
                        vo.setShowCancelFlag(Boolean.TRUE);
                    }

                    //显示晒单按钮
                    vo.setIsBuyShow(CartIsShowEnum.hide.getKey());
                    /*
                    if (SendStatusEnum.receive.getKey().equals(order.getSendStatus())) {
                        for (OrderItemVo obj : itemVoList) {
                            obj.setIsBuyShow(CartIsShowEnum.hide.getKey());
                            if (BuyShowEnum.unShow.getKey().equals(obj.getBuyShow())) {
                                obj.setIsBuyShow(CartIsShowEnum.show.getKey());
                                vo.setIsBuyShow(CartIsShowEnum.show.getKey());
                            }
                        }
                    }*/

                    vo.setItemList(itemVoList);
                    voList.add(vo);
                }
            }
        }
        return voList;
    }

    /**
     * 统计订单数
     *
     * @param query
     * @return
     */
    @Override
    public Integer selectOrderCount(OrderQuery query) {
        List<OrderInfoVo> voList = getOrderInfoVos(query);
        if (ObjectUtil.isNotEmpty(voList))
            return voList.size();
        return 0;
    }

    /**
     * 修改收货地址
     *
     * @param query
     * @return
     */
    @Override
    public boolean updateAddress(OrderQuery query) {
        limitUserOperation();
        Long customerUid = SecurityUtils.getCustomerUid();

        if (ObjectUtil.isEmpty(query.getOrderUid()))
            throw new BaseException("订单ID不能为空");
        if (ObjectUtil.isEmpty(query.getAddressId()))
            throw new BaseException("收货地址ID不能为空");
        CustomerAddressVo addressVo = iCustomerAddressService.getCustomerAddressInfo(query.getAddressId());
        if (ObjectUtil.isEmpty(addressVo) || addressVo.getCustomerUid().longValue() != customerUid)
            throw new BaseException("没有找到收货地址信息");

        OrderInfo info = this.getById(query.getOrderUid());
        if (info == null) throw new BaseException("没有找到订单信息");

        //支付一小时内未发货订单可修改地址,默认60分钟
        if (PayStatusEnum.paid.getKey().equals(info.getPayStatus())
                && SendStatusEnum.unShip.getKey().equals(info.getSendStatus())) {

            Date expire = null;
            Long minute = 60L;
            PlatformGeneralsettingsVo data = platformGeneralsettingsService.get(info.getPlatformUid());
            if (ObjectUtil.isNotEmpty(data) && ObjectUtil.isNotEmpty(data.getOrderAddress())) {
                minute = Long.parseLong(data.getOrderAddress());
            }

            expire = DateUtils.add(info.getPayTime(), minute);

            if (System.currentTimeMillis() - expire.getTime() > 0) {
                throw new BaseException("无法修改地址信息");
            }
        }


        info.setAddressUid(query.getAddressId());
        info.setUpdateTime(new Date());
        info.setUpdateUser(customerUid);
        info.setUpdateUserName(SecurityUtils.getCustomerUserName());
        return this.updateById(info);
    }

    /**
     * 修改订单发票
     *
     * @param query
     * @return
     */
    @Override
    public boolean updateInvoice(OrderQuery query) {
        if (ObjectUtil.isEmpty(query.getInvoiceId()))
            throw new BaseException("发票ID不能为空");
        if (ObjectUtil.isEmpty(query.getOrderUid()))
            throw new BaseException("订单ID不能为空");
        CustomerInvoice customerInvoice = iCustomerInvoiceService.selectCustomerInvoiceById(query.getInvoiceId().intValue());
        if (ObjectUtil.isEmpty(customerInvoice)) throw new BaseException("没有找到发票信息");
        if (customerInvoice.getCustomerId().longValue() != SecurityUtils.getCustomerUid()) {
            throw new BaseException("没有找到发票信息");
        }
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderUid(query.getOrderUid());
        orderInfo.setInvoiceUid(query.getInvoiceId());
        orderInfo.setUpdateTime(new Date());
        orderInfo.setUpdateUser(SecurityUtils.getCustomerUid());
        orderInfo.setUpdateUserName(SecurityUtils.getCustomerUserName());
        return this.updateById(orderInfo);
    }

    /**
     * 取消订单
     *
     * @param query
     * @return
     */
    @Override

    public boolean orderCancel(OrderQuery query) {
        limitUserOperation();

        if (ObjectUtil.isEmpty(query.getOrderUid()))
            throw new BaseException("订单ID不能为空");
        OrderInfo orderInfo = this.getById(query.getOrderUid());
        if (orderInfo != null && OrderStatusEnum.effect.getKey().equals(orderInfo.getOrderStatus())) {
            Date date = DateUtil.date();
            Long customerUid = SecurityUtils.getCustomerUid();
            String customerUserName = SecurityUtils.getCustomerUserName();

            if (orderInfo.getCustomerUid().longValue() == customerUid) {
                OrderInfoParent parent = orderInfoParentService.getOrderInfo(orderInfo.getParentOrderNo());

                //未支付取消是取消同一父订单下所有的子订单
                if (PayStatusEnum.unpaid.getKey().equals(orderInfo.getPayStatus())) {

                    List<OrderInfo> infoList = queryOrderByParent(orderInfo.getParentOrderNo());
                    if (ObjectUtil.isNotEmpty(infoList)) {
                        for (OrderInfo order : infoList) {
                            order.setOrderStatus(OrderStatusEnum.unPayCancel.getKey());
                            order.setCancelTime(date);
                            order.setUpdateTime(date);
                            order.setUpdateUser(customerUid);
                            order.setUpdateUserName(customerUserName);
                        }
                        this.updateBatchById(infoList);
                    } else
                        throw new BaseException("没有找到订单信息");

                } else if (PayStatusEnum.paid.getKey().equals(orderInfo.getPayStatus())
                        && SendStatusEnum.unShip.getKey().equals(orderInfo.getSendStatus())) {

                    throw new BaseException("已付款订单不能取消");
                } else
                    throw new BaseException("该订单不能取消");

            } else
                throw new BaseException("您没有权限取消该订单");
        } else
            throw new BaseException("该订单不能取消");

        return true;
    }

    /**
     * 订单收货
     *
     * @param query
     * @return
     */
    @Override
    public boolean receiveOrder(OrderQuery query) {
        limitUserOperation();

        if (ObjectUtil.isEmpty(query.getOrderUid()))
            throw new BaseException("订单ID不能为空");
        OrderInfo orderInfo = this.getById(query.getOrderUid());
        if (orderInfo != null && OrderStatusEnum.effect.getKey().equals(orderInfo.getOrderStatus())) {
            Date date = DateUtil.date();
            Long customerUid = SecurityUtils.getCustomerUid();
            String customerUserName = SecurityUtils.getCustomerUserName();
            if (orderInfo.getCustomerUid().longValue() == customerUid) {
                if (SendStatusEnum.ship.getKey().equals(orderInfo.getSendStatus())) {
                    orderInfo.setSendStatus(SendStatusEnum.receive.getKey());
                    orderInfo.setReceiveTime(date);
                    orderInfo.setUpdateTime(date);
                    orderInfo.setUpdateUser(customerUid);
                    orderInfo.setUpdateUserName(customerUserName);
                    this.updateById(orderInfo);


                    return true;
                } else
                    throw new BaseException("非待收货订单，不能收货");
            } else
                throw new BaseException("您没有该订单的收货权限");
        } else
            throw new BaseException("该订单不能收货");

    }

    /**
     * 订单延迟收货
     *
     * @param query
     * @return
     */
    @Override
    public boolean delayReceive(OrderQuery query) {
        if (ObjectUtil.isEmpty(query.getOrderUid()))
            throw new BaseException("订单ID不能为空");
        String key = user_delay_order + query.getOrderUid();
        if (redisService.incr(key, ONEMONTH) > 1)
            throw new BaseException("单个订单仅限延迟一次收货时间");
        try {
            OrderInfo orderInfo = this.getById(query.getOrderUid());
            if (orderInfo != null && OrderStatusEnum.effect.getKey().equals(orderInfo.getOrderStatus())) {
                Date date = DateUtil.date();
                Long customerUid = SecurityUtils.getCustomerUid();
                String customerUserName = SecurityUtils.getCustomerUserName();
                Long customerPlatformUid = SecurityUtils.getCustomerPlatformUid();
                Long customerAccountUid = SecurityUtils.getCustomerAccountUid();
                if (orderInfo.getCustomerUid().longValue() == customerUid) {
                    if (orderInfo.getAutoReceiveTime() == null) {
                        throw new BaseException("缺少自动收货时间，不能延迟收货");
                    }
                    if (SendStatusEnum.ship.getKey().equals(orderInfo.getSendStatus())) {
                        Long autoDate = 0L;
                        OrderShipAuto orderShipAuto = shipAutoService.selectByPlatformUid(customerPlatformUid);
                        if (ObjectUtil.isNotEmpty(orderShipAuto))
                            autoDate = orderShipAuto.getDelayedDate();
                        if (autoDate == null || autoDate == 0L) autoDate = 5L;//默认延迟5天

                        Date autoReceiveTime = DateUtils.addDay(orderInfo.getAutoReceiveTime(), autoDate.intValue());
                        orderInfo.setAutoReceiveTime(autoReceiveTime);

                        redisService.incr(key, ONEMONTH);
                        return this.updateById(orderInfo);
                    } else
                        throw new BaseException("非待收货订单，不能延迟收货");
                } else
                    throw new BaseException("您没有该订单的延迟收货权限");
            } else
                throw new BaseException("该订单不能延迟收货");
        } finally {
            redisService.decr(key);
        }
    }

    /**
     * 订单评价
     *
     * @param query
     * @return
     */
    @Override
    public boolean orderComment(OrderQuery query) {
        if (ObjectUtil.isEmpty(query.getOrderUid()))
            throw new BaseException("订单ID不能为空");
        OrderInfo orderInfo = this.getById(query.getOrderUid());
        if (orderInfo != null && OrderStatusEnum.effect.getKey().equals(orderInfo.getOrderStatus())) {
            Date date = DateUtil.date();
            Long customerUid = SecurityUtils.getCustomerUid();
            String customerUserName = SecurityUtils.getCustomerUserName();
            Long customerPlatformUid = SecurityUtils.getCustomerPlatformUid();
            Long customerAccountUid = SecurityUtils.getCustomerAccountUid();
            if (orderInfo.getCustomerUid().longValue() == customerUid) {
                if (CommentStatusEnum.unComment.getKey().equals(orderInfo.getCommentStatus())) {
                    orderInfo.setCommentTime(date);
                    orderInfo.setCommentStatus(CommentStatusEnum.comment.getKey());
                    this.updateById(orderInfo);


                    List<ProductCommentApiVo> comments = query.getComments();
                    if (ObjectUtil.isNotEmpty(comments)) {

                        List<OrderItemVo> itemVoList = itemService.getByOrderUid(orderInfo.getOrderUid());
                        if (ObjectUtil.isNotEmpty(itemVoList)) {
                            ProductCommentApiVo commentApiVo = null;
                            List<ProductCommentApiVo> commentApiVoList = new ArrayList<>();

                            for (OrderItemVo itemVo : itemVoList) {
                                commentApiVo = null;
                                for (ProductCommentApiVo vo : comments) {
                                    //如果没有sku则对比商品ID
                                    if (ObjectUtil.isEmpty(vo.getSkuUid())) {
                                        if (ObjectUtil.isNotEmpty(vo.getProductUid()) && vo.getProductUid().longValue() == itemVo.getProUid()) {
                                            commentApiVo = vo;
                                            break;
                                        }
                                    } else {
                                        if (ObjectUtil.isNotEmpty(vo.getSkuUid()) && vo.getSkuUid().longValue() == itemVo.getSkuUid()) {
                                            commentApiVo = vo;
                                            break;
                                        }
                                    }
                                }

                                if (commentApiVo == null) {
                                    commentApiVo = new ProductCommentApiVo();
                                    commentApiVo.setImagesUrl("");
                                    commentApiVo.setCommentContent("");
                                }

                                commentApiVo.setLogisticsScore(query.getLogisticsScore());
                                commentApiVo.setServiceScore(query.getServiceScore());
                                commentApiVo.setProductUid(itemVo.getProUid());
                                commentApiVo.setProductName(itemVo.getProName());
                                commentApiVo.setProductImgUrl(itemVo.getImgUrl());
                                commentApiVo.setMemberUid(customerUid);
                                commentApiVo.setOrderUid(orderInfo.getOrderUid());
                                commentApiVo.setOrderNo(orderInfo.getOrderNo());
                                commentApiVo.setSkuUid(itemVo.getSkuUid());
                                commentApiVo.setPlatformUid(customerPlatformUid);
                                commentApiVo.setCommentTime(DateUtils.formate(date));
                                commentApiVoList.add(commentApiVo);
                            }
                            //logger.info("现在开始调用评论服务1==>");
                            //logger.info("现在开始调用评论服务2==>{}",JSONArray.toJSONString(commentApiVoList));

                            boolean b = iProductCommentService.insertProductComment(commentApiVoList);
                            if (!b) throw new BaseException("添加评论失败！");
                        }
                    }
                } else
                    throw new BaseException("该订单已评价");
            } else
                throw new BaseException("您没有该订单的评价权限");
        } else
            throw new BaseException("无法评价该订单");
        return true;
    }

    @Override
    public boolean orderFinish(OrderQuery query) {
        orderPaymentSuccess(orderInfoParentService.getOrderInfo(query.getParentOrderNo()), null);

        return false;
    }

    /**
     * 订单物流信息
     *
     * @param query
     * @return
     */
    @Override
    public OrderTraceVo getTraceInfo(OrderQuery query) {
        QueryWrapper<OrderInfo> queryWrapper = Wrappers.query();
        queryWrapper.eq("customer_uid", query.getCustomerUid());
        if (query.getOrderUid() != null)
            queryWrapper.eq("order_uid", query.getOrderUid());
        if (ObjectUtil.isNotEmpty(query.getOrderNo()))
            queryWrapper.eq("order_no", query.getOrderNo());

        OrderTraceVo traceVo = null;
        List<OrderInfo> orderInfoList = orderInfoMapper.selectList(queryWrapper);

        if (ObjectUtil.isNotEmpty(orderInfoList)) {
            OrderInfo orderInfo = orderInfoList.get(0);

            OrderShipDeliverVo deliver = deliverService.getNormalDeliver(orderInfo);
            if (deliver != null) {
                if (ObjectUtil.isNotEmpty(deliver.getExpressCode()) && ObjectUtil.isNotEmpty(deliver.getExpressNo())) {
                    traceVo = orderTraceService.getTraceInfo(deliver.getExpressCode(), deliver.getExpressNo());
                }
            }

            if (traceVo == null) {
                traceVo = new OrderTraceVo();
                traceVo.setTraces(new ArrayList<>());
            }


            TraceVo vo = new TraceVo();
            vo.setAcceptTime(DateUtils.formate(orderInfo.getPayTime()));
            vo.setAcceptStation("支付订单");
            vo.setAction(TraceStatusEnum.payOrder.getKey());
            traceVo.getTraces().add(vo);
            vo = new TraceVo();
            vo.setAcceptTime(DateUtils.formate(orderInfo.getCreateTime()));
            vo.setAcceptStation("创建订单");
            vo.setAction(TraceStatusEnum.createOrder.getKey());
            traceVo.getTraces().add(vo);

            logger.info("\n============物流轨迹：{}===========\n", JSONObject.toJSONString(traceVo.getTraces()));
            if (deliver != null) {
                deliver.setContent(JSONArray.toJSONString(traceVo.getTraces()));
                OrderShipDeliver shipDeliver = new OrderShipDeliver();
                BeanUtils.copyProperties(deliver, shipDeliver);
                deliverService.updateById(shipDeliver);
            }

        } else throw new BaseException("没有找到订单信息");

        return traceVo;
    }


    /**
     * 根据订单ID或者订单编号获得订单信息
     *
     * @param orderUid
     * @param orderNo
     * @return
     */
    public OrderInfo getOrder(Long orderUid, String orderNo) {
        if (ObjectUtil.isEmpty(orderUid) && ObjectUtil.isEmpty(orderNo))
            throw new BaseException("订单ID或订单编号不能为空");

        QueryWrapper<OrderInfo> queryWrapper = Wrappers.query();
        if (ObjectUtil.isNotEmpty(orderUid))
            queryWrapper.eq("order_uid", orderUid);
        if (ObjectUtil.isNotEmpty(orderNo))
            queryWrapper.eq("order_no", orderNo);
        queryWrapper.eq("order_status", DataStatus.valid.getKey());

        List<OrderInfo> infoList = orderInfoMapper.selectList(queryWrapper);
        if (ObjectUtil.isNotEmpty(infoList))
            return infoList.get(0);
        return null;
    }

    /**
     * 订单列表查询状态
     */
    private void queryStatus(OrderInfo orderInfo) {

        if (OrderQueryStatusEnum.unpay.getKey().equals(orderInfo.getQueryStatus())) {
            orderInfo.setPayStatus(PayStatusEnum.unpaid.getKey());
        } else if (OrderQueryStatusEnum.unsend.getKey().equals(orderInfo.getQueryStatus())) {
            orderInfo.setPayStatus(PayStatusEnum.paid.getKey());
            orderInfo.setSendStatus(SendStatusEnum.unShip.getKey());
        } else if (OrderQueryStatusEnum.unreceive.getKey().equals(orderInfo.getQueryStatus())) {
            orderInfo.setPayStatus(PayStatusEnum.paid.getKey());
            orderInfo.setSendStatus(SendStatusEnum.ship.getKey());
        } else if (OrderQueryStatusEnum.uncomment.getKey().equals(orderInfo.getQueryStatus())) {
            orderInfo.setPayStatus(PayStatusEnum.paid.getKey());
            orderInfo.setSendStatus(SendStatusEnum.receive.getKey());
            orderInfo.setCommentStatus(CommentStatusEnum.unComment.getKey());
        }
    }

    /**
     * 砍价订单
     *
     * @param query
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public boolean addBargainOrder(ActivityInfoQuery query) {
        logger.info("\n========== 砍价订单参数:{}==========\n", JSONObject.toJSONString(query));

        OrderInfo info = new OrderInfo();
        BeanUtils.copyProperties(query, info);

        Date now = new Date();
        String parentOrderNo = createParentOrderNo();
        //生成父订单
        OrderInfoParent parent = new OrderInfoParent();
        parent.setParentOrderNo(parentOrderNo);
        parent.setParentAmount(query.getActivityPrice());
        parent.setFreightAmount(0L);
        parent.setDiscountAmount(query.getActivityPrice());
        parent.setPayAmount(0L);
        parent.setPayMethod(query.getPayMethod());
        parent.setPayStatus(PayStatusEnum.unpaid.getKey());
        parent.setCreateTime(now);
        parent.setProfitSharing(ProfitSharingEnum.N.toString());
        parent.setCustomerId(query.getCustomerUid());
        parent.setPlatformId(query.getPlatformUid());
        parent.setIsRecharge(OrderRechargeEnum.good.getKey());
        orderInfoParentService.save(parent);




        info.setOrderType(query.getActivityType());
        info.setOrderNo(createOrderNo());
        info.setParentOrderNo(parentOrderNo);
        info.setOrderStatus(OrderStatusEnum.effect.getKey());
        info.setPayStatus(PayStatusEnum.unpaid.getKey());
        info.setPayMethod(query.getPayMethod());
        info.setPlatSource(query.getPlatSource());
        info.setOrderAmount(query.getActivityPrice());
        info.setPayAmount(0L);
        info.setFreightAmount(0L);
        info.setDiscountAmount(query.getActivityPrice());
        info.setUseCouponAmount(0L);
        info.setPayByBalance(0L);
        info.setPayByScore(0L);
        info.setPayByRedBag(0L);
        info.setCreateTime(now);
        info.setBuyMes("砍价免费拿");
        info.setDeliverMethod(DeliverMethodEnum.express.getKey());
        info.setAddressUid(query.getAddressUid());
        info.setUpdateUser(info.getCustomerUid());
        info.setUpdateUserName(info.getCustomerName());
        info.setUpdateTime(now);
        if (this.save(info)) {
            OrderInfoItem item = new OrderInfoItem();
            item.setSupplierUid(info.getSupplierUid());
            item.setOrderUid(info.getOrderUid());
            item.setActivityUid(query.getActivityUid());
            item.setActivityProUid(query.getActivityProUid());
            item.setProUnit(query.getProUnit());
            item.setProNo(query.getProNo());
            item.setProUid(query.getProUid());
            item.setProName(query.getProName());
            item.setImgUrl(query.getImgUrl());
            item.setPrice(info.getOrderAmount());
            item.setItemNumber(1L);
            item.setItemAmount(info.getOrderAmount());
            item.setPayAmount(0L);
            item.setDiscountAmount(info.getOrderAmount());
            item.setCartUid(query.getCarUids());
            item.setSettlementStatus(SettlementEnum.unSettlement.getKey());
            item.setSaleStatus(SaleStatusEnum.normal.getKey());
            item.setDataStatus(DataStatus.valid.getKey());
            item.setCreateUid(query.getCustomerUid());
            item.setCreateTime(now);
            itemService.save(item);



            return true;
        }
        throw new BaseException("生成订单失败，请稍后再试!");
    }

    /**
     * 砍价成功修改订单状态
     *
     * @param query
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public boolean updateBargainOrder(ActivityInfoQuery query) {
        if (ObjectUtil.isEmpty(query.getJoinUid()))
            throw new BaseException("缺少活动参与参数");

        Date now = new Date();

        QueryWrapper<OrderInfo> queryWrapper = Wrappers.query();
        queryWrapper.eq("JOIN_UID", query.getJoinUid());
        queryWrapper.eq("ORDER_STATUS", DataStatus.valid.getKey());
        queryWrapper.eq("ORDER_TYPE", ActivityTypeEnum.bargain.getKey());
        List<OrderInfo> list = orderInfoMapper.selectList(queryWrapper);
        if (ObjectUtil.isEmpty(list))
            throw new BaseException("没有找到活动订单信息");

        OrderInfo orderInfo = list.get(0);
        orderInfo.setPayStatus(PayStatusEnum.paid.getKey());
        orderInfo.setPayTime(now);

        orderInfoParentService.updatePayStatus(orderInfo.getParentOrderNo());

        List<OrderItemVo> itemVoList = itemService.getByOrderUid(orderInfo.getOrderUid());
        if (ObjectUtil.isNotEmpty(itemVoList)) {
            for (OrderItemVo item : itemVoList) {
                sendLogMsg(ProductOptType.buy.getKey(), orderInfo.getPlatformUid(), orderInfo.getCustomerUid(), item.getOrderType(), item.getProUid(), item.getItemNumber());
            }
        }

        return this.updateById(orderInfo);
    }

    /**
     * 购买会员
     *
     * @param settle
     * @return
     */
    @Override
    public JSONObject buyVip(OrderSettlementVo settle) {
        //用户层面限流
        limitUserOperation();

        if (ObjectUtil.isEmpty(settle.getLevelId()))
            throw new BaseException("缺少会员等级参数");

        logger.info("\n=========购买会员参数：{}==========\n", settle);

        //获取等级权益信息
        CustomerLevelOpenVo level = iCustomerLevelService.getByCustomerLevelInfoID(settle.getLevelId());
        if (level == null || ObjectUtil.isNull(level.getPaymentRules())) throw new BaseException("没有找到会员等级权益信息");

        BigDecimal amount = level.getPaymentRules().getPrice();
        if (amount == null || amount.compareTo(BigDecimal.ZERO) < -1 || amount.compareTo(BigDecimal.ZERO) == 0)
            throw new BaseException("支付金额需大于0元");
        BigDecimal oneHundred = new BigDecimal(100);
        amount = amount.multiply(oneHundred);
        logger.info("\n=========需要支付的金额：{}==========\n", amount.longValue());
        settle.setShopAmount(amount.longValue());
        settle.setIsRecharge(OrderRechargeEnum.recharge.getKey());
        settle.setScoreAmount(0L);
        OrderInfoParent parent = createParentOrder(settle);

        Date now = new Date();
        OrderRecharge recharge = new OrderRecharge();
        recharge.setLevelId(settle.getLevelId());
        recharge.setPlatformUid(settle.getPlatformId());
        recharge.setRechargeNo(createRechargeOrderNo());
        recharge.setParentOrderNo(parent.getParentOrderNo());
        recharge.setCustomerUid(settle.getCustomerId());
        recharge.setCustomerName(settle.getCustomerName());
        recharge.setPhone(settle.getPhone());
        recharge.setOrderStatus(OrderStatusEnum.effect.getKey());
        recharge.setPayStatus(PayStatusEnum.unpaid.getKey());
        recharge.setPayMethod(settle.getPayMethod());
        recharge.setPlatSource(settle.getPlatSource());
        recharge.setOrderAmount(amount.longValue());
        recharge.setPayAmount(amount.longValue());
        recharge.setCurrencyUnit("RMB");
        recharge.setCreateTime(now);
        recharge.setBuyMes(settle.getBuyerMsg());
        recharge.setIp(SecurityUtils.getCustomerClientIp());
        //店铺配置获取支付超时时间
        Date expire = null;
        PlatformGeneralsettingsVo data = platformGeneralsettingsService.get(recharge.getPlatformUid());
        if (ObjectUtil.isNotEmpty(data)) {
            expire = DateUtils.add(now, Long.parseLong(data.getWaitOrderPayment()));
        }
        if (expire == null) expire = DateUtils.add(60L);
        recharge.setExpireDate(expire);
        if (rechargeService.save(recharge)) {


            return callPayment(parent, settle);
        }
        throw new BaseException("创建订单失败，请稍后再试");
    }


    @Override
    public JSONObject rechargeMoney(OrderSettlementVo settle) {
        //用户层面限流
        limitUserOperation();

        Long amount = 0L;
        Long totalAmount = 0L;

        CustomerInfo customerInfo = iCustomerInfoService.getById(SecurityUtils.getCustomerUid());
        if (customerInfo == null){
            throw new RuntimeException("没有找到用户信息");
        }

        amount = settle.getScore()*100;
        totalAmount = amount;
        if (amount == null || amount <= 0)
            throw new BaseException("支付金额需大于0元");
        settle.setCustomerName(SecurityUtils.getCustomerUserName());
        settle.setShopAmount(amount);
        settle.setIsRecharge(OrderRechargeEnum.recharge.getKey());
        OrderInfoParent parent = createParentOrder(settle);
        Date now = new Date();
        OrderRecharge recharge = new OrderRecharge();
        recharge.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
        recharge.setRechargeNo(createRechargeOrderNo());
        recharge.setRechargeName("扫码兑换积分");
        recharge.setParentOrderNo(parent.getParentOrderNo());
        recharge.setCustomerUid(SecurityUtils.getCustomerUid());
        recharge.setCustomerName(customerInfo.getCustomerName());
        recharge.setPhone(customerInfo.getPhone());
        //recharge.setLevelId(info.getMemberLevel());
        recharge.setOrderStatus(OrderStatusEnum.effect.getKey());
        recharge.setPayStatus(PayStatusEnum.unpaid.getKey());
        recharge.setPayMethod(settle.getPayMethod());
        recharge.setPlatSource(settle.getPlatSource());
        recharge.setOrderAmount(totalAmount);
        recharge.setPayAmount(amount);
        recharge.setCurrencyUnit("RMB");
        recharge.setCreateTime(now);
        recharge.setBuyMes(settle.getBuyerMsg());
        recharge.setIp(SecurityUtils.getCustomerClientIp());
        recharge.setScore(settle.getScore());
        recharge.setIsShared(ProfitsharingStatusEnum.wait.getKey());
        recharge.setProfitSharing(ProfitSharingEnum.N.toString());
        //店铺配置获取支付超时时间
        Date expire = DateUtils.add(60L);
        recharge.setExpireDate(expire);
        if (rechargeService.save(recharge)) {
            return callPayment(parent, settle);
        }
        throw new BaseException("创建订单失败，请稍后再试");
    }
    /**
     * 充值
     *
     * @param settle
     * @return
     */
    @Override
    public JSONObject toRecharge(OrderSettlementVo settle) {
        //用户层面限流
        limitUserOperation();

        Long amount = 0L;
        Long totalAmount = 0L;

        RechargeInfo info = rechargeInfoService.getById(settle.getRechargeId());
        if (info == null || !info.getDataStatus().equals(DataStatus.valid.getKey())) {
            throw new BaseException("没有找到充值项");
        }

        CustomerInfo customerInfo = iCustomerInfoService.getById(SecurityUtils.getCustomerUid());
        if (customerInfo == null){
            throw new RuntimeException("没有找到用户信息");
        }

        amount = info.getRechargeMoney();
        totalAmount = amount;
        if (amount == null || amount <= 0)
            throw new BaseException("支付金额需大于0元");
        settle.setCustomerName(SecurityUtils.getCustomerUserName());
        settle.setShopAmount(amount);
        settle.setIsRecharge(OrderRechargeEnum.recharge.getKey());
        OrderInfoParent parent = createParentOrder(settle);
        Date now = new Date();
        OrderRecharge recharge = new OrderRecharge();
        recharge.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
        recharge.setRechargeNo(createRechargeOrderNo());
        recharge.setRechargeName(info.getRechargeName());
        recharge.setParentOrderNo(parent.getParentOrderNo());
        recharge.setCustomerUid(SecurityUtils.getCustomerUid());
        recharge.setCustomerName(customerInfo.getCustomerName());
        recharge.setPhone(customerInfo.getPhone());
        recharge.setLevelId(info.getMemberLevel());
        recharge.setOrderStatus(OrderStatusEnum.effect.getKey());
        recharge.setPayStatus(PayStatusEnum.unpaid.getKey());
        recharge.setPayMethod(settle.getPayMethod());
        recharge.setPlatSource(settle.getPlatSource());
        recharge.setOrderAmount(totalAmount);
        recharge.setPayAmount(amount);
        recharge.setCurrencyUnit("RMB");
        recharge.setCreateTime(now);
        recharge.setBuyMes(settle.getBuyerMsg());
        recharge.setIp(SecurityUtils.getCustomerClientIp());
        recharge.setRechargeId(info.getRechargeId());
        recharge.setFirstDouble(info.getFirstDouble());
        recharge.setGoldCoin(info.getGoldCoin());
        recharge.setSilverCoin(info.getSilverCoin());
        recharge.setScore(info.getScore());
        recharge.setRechargeDesc(info.getRechargeDesc());
        recharge.setStoreId(settle.getStoreId());
        recharge.setIsShared(ProfitsharingStatusEnum.wait.getKey());
        recharge.setProfitSharing(ProfitSharingEnum.N.toString());
        //店铺配置获取支付超时时间
        Date expire = DateUtils.add(60L);

        recharge.setExpireDate(expire);
        if (rechargeService.save(recharge)) {
            return callPayment(parent, settle);
        }
        throw new BaseException("创建订单失败，请稍后再试");

    }

    /**
     * 统计代办订单
     *
     * @param customerUid
     * @return
     */
    @Override
    public OrderCountVo orderCount(Long customerUid) {
        OrderCountVo vo = new OrderCountVo();

        if (ObjectUtil.isEmpty(customerUid))
            return vo;

        QueryWrapper<OrderInfo> unPay = Wrappers.query();
        unPay.eq("customer_uid", customerUid);
        unPay.eq("order_status", OrderStatusEnum.effect.getKey());
        unPay.eq("pay_status", PayStatusEnum.unpaid.getKey());
        unPay.ne("order_type", ActivityTypeEnum.bargain.getKey());
        vo.setUnPayCount(orderInfoMapper.selectCount(unPay));

        QueryWrapper<OrderInfo> unSend = Wrappers.query();
        unSend.eq("customer_uid", customerUid);
        unSend.eq("order_status", OrderStatusEnum.effect.getKey());
        unSend.eq("pay_status", PayStatusEnum.paid.getKey());
        unSend.eq("send_status", SendStatusEnum.unShip.getKey());
        vo.setUnSendCount(orderInfoMapper.selectCount(unSend));

        QueryWrapper<OrderInfo> unReceive = Wrappers.query();
        unReceive.eq("customer_uid", customerUid);
        unReceive.eq("order_status", OrderStatusEnum.effect.getKey());
        unReceive.eq("pay_status", PayStatusEnum.paid.getKey());
        unReceive.eq("send_status", SendStatusEnum.ship.getKey());
        vo.setUnReceiveCount(orderInfoMapper.selectCount(unReceive));

        QueryWrapper<OrderInfo> unComment = Wrappers.query();
        unComment.eq("customer_uid", customerUid);
        unComment.eq("order_status", OrderStatusEnum.effect.getKey());
        unComment.eq("pay_status", PayStatusEnum.paid.getKey());
        unComment.eq("send_status", SendStatusEnum.receive.getKey());
        unComment.eq("comment_status", CommentStatusEnum.unComment.getKey());
        vo.setUnCommentCount(orderInfoMapper.selectCount(unComment));

        return vo;
    }

    /**
     * 撤销发货
     *
     * @param query
     * @return
     */
    @Override
    public boolean revokeShip(OrderQuery query) {
        if (ObjectUtil.isEmpty(query.getOrderUid()))
            throw new BaseException("缺少订单ID参数");

        OrderInfo orderInfo = this.getById(query.getOrderUid());
        if (ObjectUtil.isNull(orderInfo))
            throw new BaseException("没有找到订单信息");
        if (!SendStatusEnum.ship.getKey().equals(orderInfo.getSendStatus()))
            throw new BaseException("不是已发货的订单，无法撤销发货");

        Date date = DateUtil.date();
        Long accountUid = SecurityUtils.getUserId();
        String accountName = SecurityUtils.getUsername();

        orderInfo.setSendTime(null);
        orderInfo.setSendStatus(SendStatusEnum.unShip.getKey());
        orderInfo.setUpdateUser(accountUid);
        orderInfo.setUpdateUserName(accountName);
        orderInfo.setUpdateTime(date);

        UpdateWrapper<OrderShipDeliver> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("ORDER_UID", orderInfo.getOrderUid());
        updateWrapper.eq("DELIVER_TYPE", DeliverTypeEnum.normal.getKey());
        updateWrapper.set("DATA_STATUS", DataStatus.invalid.getKey());
        deliverService.update(updateWrapper);

        return updateById(orderInfo);
    }

    /**
     * 取消发货
     *
     * @param query
     * @return
     */
    @Override
    public boolean cancelShip(OrderQuery query) {
        if (ObjectUtil.isEmpty(query.getOrderUid()))
            throw new BaseException("缺少订单ID参数");

        OrderInfo orderInfo = this.getById(query.getOrderUid());
        if (ObjectUtil.isNull(orderInfo))
            throw new BaseException("没有找到订单信息");

        if (!SendStatusEnum.ship.getKey().equals(orderInfo.getSendStatus()))
            throw new BaseException("不是已发货的订单，无法取消发货");

        Date date = DateUtil.date();
        Long accountUid = SecurityUtils.getUserId();
        String accountName = SecurityUtils.getUsername();

        orderInfo.setSendTime(null);
        orderInfo.setSendStatus(SendStatusEnum.cancel.getKey());
        orderInfo.setUpdateUser(accountUid);
        orderInfo.setUpdateUserName(accountName);
        orderInfo.setUpdateTime(date);

        UpdateWrapper<OrderShipDeliver> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("ORDER_UID", orderInfo.getOrderUid());
        updateWrapper.eq("DELIVER_TYPE", DeliverTypeEnum.normal.getKey());
        updateWrapper.set("DATA_STATUS", DataStatus.invalid.getKey());
        deliverService.update(updateWrapper);

        return updateById(orderInfo);
    }

    /**
     * 获取打单模板
     *
     * @param orderUid
     * @return
     */
    @Override
    public String getTemplate(Long orderUid) throws Exception {
        if (ObjectUtil.isEmpty(orderUid))
            throw new BaseException("缺少订单ID参数信息");
        OrderInfo orderInfo = this.getById(orderUid);
        if (ObjectUtil.isNull(orderInfo))
            throw new BaseException("没有找到订单信息");

        OrderInfoVo vo = selectOrderInfoById(orderUid);

        return intimidate(vo);
    }



    @Override
    public void sendLogMsg(String optType, Long platformUid, Long customerUid, String proType, Long proUid, Long amount) {

    }


    @Override
    public JSONArray addRemark(OrderQuery query) {
        if (ObjectUtil.isEmpty(query.getOrderUid()))
            throw new BaseException("缺少订单ID参数");
        if (ObjectUtil.isEmpty(query.getRemark()))
            throw new BaseException("订单备注不能为空");

        OrderInfo orderInfo = this.getById(query.getOrderUid());

        JSONArray array = null;
        if (ObjectUtil.isNotEmpty(orderInfo.getRemark())) {
            if (orderInfo.getRemark().startsWith("[")){
                array = JSONObject.parseArray(orderInfo.getRemark());
            }else{
                array = new JSONArray();
                array.add(orderInfo.getRemark()+";");
            }
        }
        if (array == null) array = new JSONArray();

        array.add(query.getRemark() + "     .     " + DateUtil.now() + "     .     " + SecurityUtils.getUsername() + ";");

        orderInfo.setRemark(JSONArray.toJSONString(array));
        this.updateById(orderInfo);

        return array;
    }

    @Override
    public boolean addInvoice(OrderInvoice invoice) {
        if (ObjectUtil.isEmpty(invoice.getOrderUid()))
            throw new BaseException("缺少订单ID参数");

        OrderInfo orderInfo = this.getById(invoice.getOrderUid());
        if (orderInfo == null) throw new BaseException("没有找到订单信息");
        orderInfo.setInvoiceStatus(InvoiceStatusEnum.invoice.getKey());
        this.updateById(orderInfo);

        Date now = new Date();
        invoice.setPlatformUid(SecurityUtils.getPlatformId());
        invoice.setDataStatus(DataStatus.valid.getKey());
        invoice.setUpdateUser(SecurityUtils.getUserId());
        invoice.setUpdateName(SecurityUtils.getUsername());
        invoice.setUpdateTime(now);

        return invoiceService.save(invoice);
    }

    @Override
    public List<Long> getOrderUidByNo(OrderQuery query) {

        return orderInfoMapper.getOrderUidByNo(query);
    }

    /**
     * 有效时间内，支付成功订单数,购买次数，订单总额
     *
     * @param query
     * @return
     */
    @Override
    public List<ProductOptVo> getOrderCount(CustomerGroupDefinitionQuery query) {
        if (ObjectUtil.isEmpty(query.getPlatformId()))
            throw new BaseException("缺少平台ID参数");
        if (ObjectUtil.isEmpty(query.getDefinitionType()))
            throw new BaseException("缺少特征类型参数");

        List<ProductOptVo> optVoList = null;

        if (CustomerGroupTypeEnum.validBugNumber.getKey().equals(query.getDefinitionType())) {

            optVoList = orderInfoParentService.getOptCount(query);

        } else if (CustomerGroupTypeEnum.validBuyMoney.getKey().equals(query.getDefinitionType())) {

            optVoList = orderInfoMapper.getOptCount(query);

            if (ObjectUtil.isNotEmpty(optVoList)) {
                List<ProductOptVo> list = postSaleService.getOptCount(query);
                if (ObjectUtil.isNotEmpty(list)) {
                    for (ProductOptVo optVo : optVoList) {
                        for (ProductOptVo obj : list) {
                            if (optVo.getMemberUid() == obj.getMemberUid()) {
                                optVo.setOrderAmount(optVo.getOrderAmount() - obj.getOrderAmount());
                            }
                        }
                    }
                }
            }

        } else if (CustomerGroupTypeEnum.notRefundOrderNumber.getKey().equals(query.getDefinitionType())) {

            optVoList = orderInfoMapper.getOptCount(query);

        }

        return optVoList;
    }

    /**
     * 赠品订单
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Long giftOrder(ActivityGiftVo vo) {
        logger.info("\n========== 赠品订单参数:{}==========\n", JSONObject.toJSONString(vo));

        Date now = new Date();
        Long amount = Convert.toLong(vo.getRetailPrice()) * vo.getNumber();

        String parentOrderNo = createParentOrderNo();
        //生成父订单
        OrderInfoParent parent = new OrderInfoParent();
        parent.setParentOrderNo(parentOrderNo);
        parent.setParentAmount(amount);
        parent.setFreightAmount(0L);
        parent.setDiscountAmount(amount);
        parent.setPayAmount(0L);
        parent.setPayMethod(PayMethodEnum.wechat.getKey());
        parent.setPayStatus(PayStatusEnum.paid.getKey());
        parent.setCreateTime(now);
        parent.setProfitSharing(ProfitSharingEnum.N.toString());
        parent.setCustomerId(vo.getCustomerUid());
        parent.setPlatformId(vo.getPlatformUid());
        parent.setIsRecharge(OrderRechargeEnum.good.getKey());
        orderInfoParentService.save(parent);

        //生成子订单
        OrderInfo info = new OrderInfo();
        if (vo.getSupplierUid() != null && vo.getSupplierUid() > 0) {

        }

        info.setOrderType(OrderTypeEnum.gift.getKey());
        info.setOrderNo(createOrderNo());
        info.setParentOrderNo(parentOrderNo);
        info.setOrderStatus(OrderStatusEnum.effect.getKey());
        info.setPayStatus(PayStatusEnum.paid.getKey());
        info.setPayMethod(PayMethodEnum.wechat.getKey());
        info.setPlatSource(PlatSourceEnum.applet.getKey());
        info.setOrderAmount(amount);
        info.setPayAmount(0L);
        info.setFreightAmount(0L);
        info.setDiscountAmount(amount);
        info.setUseCouponAmount(0L);
        info.setPayByBalance(0L);
        info.setPayByScore(0L);
        info.setPayByRedBag(0L);
        info.setCreateTime(now);
        info.setPayTime(now);
        info.setBuyMes("赠品");
        info.setDeliverMethod(DeliverMethodEnum.express.getKey());
        info.setAddressUid(vo.getUserAddressid());
        info.setCustomerUid(vo.getCustomerUid());
        info.setCustomerName(vo.getCustomerName());
        info.setUpdateUser(info.getCustomerUid());
        info.setUpdateUserName(info.getCustomerName());
        info.setUpdateTime(now);
        info.setProfitSharing(ProfitSharingEnum.N.name());
        if (this.save(info)) {
            OrderInfoItem item = new OrderInfoItem();
            item.setSupplierUid(info.getSupplierUid());
            item.setOrderUid(info.getOrderUid());
            item.setProUnit(vo.getProUnit());
            item.setProNo(vo.getProNo());
            item.setProUid(vo.getProUid());
            item.setProName(vo.getProName());
            item.setImgUrl(vo.getProImg());
            item.setPrice(Convert.toLong(vo.getRetailPrice()));
            item.setItemNumber(vo.getNumber());
            item.setItemAmount(info.getOrderAmount());
            item.setPayAmount(0L);
            item.setDiscountAmount(info.getOrderAmount());
            item.setSettlementStatus(SettlementEnum.unSettlement.getKey());
            item.setSaleStatus(SaleStatusEnum.normal.getKey());
            item.setDataStatus(DataStatus.valid.getKey());
            item.setCreateUid(vo.getCustomerUid());
            item.setCreateTime(now);
            itemService.save(item);
            return info.getOrderUid();
        } else
            throw new BaseException("生成赠品订单失败！");
    }

    @Override
    public boolean checkOrder(Long customerId) {
        QueryWrapper<OrderInfo> queryWrapper = Wrappers.query();
        queryWrapper.eq("CUSTOMER_UID", customerId);
        queryWrapper.eq("PAY_STATUS", PayStatusEnum.paid.getKey());
        queryWrapper.eq("ORDER_STATUS", OrderStatusEnum.effect.getKey());
        List<OrderInfo> list = orderInfoMapper.selectList(queryWrapper);
        if (ObjectUtil.isNotEmpty(list))
            return true;
        return false;
    }


    /**
     * 封装模板
     *
     * @param vo
     * @return
     * @throws Exception
     */
    private String intimidate(OrderInfoVo vo) throws Exception {
        if (ObjectUtil.isEmpty(vo.getItemList()) || ObjectUtil.isEmpty(vo.getCustomerAddressVo()))
            return "";

        String goods = "";
        //支付总额
        BigDecimal payAmount = new BigDecimal(0);

        for (OrderItemVo item : vo.getItemList()) {
            int i = 1;

            //出库价格/成本价
            BigDecimal costAmount = new BigDecimal(item.getCostPrice() * item.getItemNumber());
            goods += "<tr>" +
                    "<td class=\"tx1\" >" + i + "</td>" +
                    "<td class=\"tx2\" >" + item.getProNo() + "</td>" +
                    "<td class=\"tx4\" >" + item.getProName() + item.getSkuDesc() + "</td>" +
                    "<td class=\"tx2\" >" + item.getItemNumber() + item.getProUnit() + "</td>" +
                    "<td class=\"tx3\" >" + item.getItemNumber() + item.getProUnit() + "</td>" +
                    "<td class=\"tx3\" >" + MoneyUtils.changeF2Y(item.getPrice()) +
                    "<td class=\"tx2\" >" + MoneyUtils.changeF2Y(costAmount) + "</td>" +
                    "<td class=\"tx2\" ></td>" +
                    "</tr>";

            payAmount = payAmount.add(costAmount);
            i++;
        }

//        payAmount=payAmount.divide(new BigDecimal("100"));

        String remark = vo.getRemark() != null ? vo.getRemark() : "小心轻放";
        //打单时间
        String printTime = DateUtils.formate(new Date());

        String str = "<!DOCTYPE html><html lang='zh-CN'><!--100*150,90--><head><meta charset='UTF-8'><style>" +
                "html,body {width: 750px;height: 400px;} " +
                "* {margin: 0;padding: 0;font-family: 'Microsoft YaHei';-webkit-text-size-adjust: none;}" +
                ".print_paper {border: none;border-collapse: collapse;width: 100%;margin-top: -1px;table-layout: fixed;}" +
                ".print_paper td {border: solid #000 1px;padding: 0 5px;overflow: hidden;}" +
                ".table_first {margin-top: 0;}" +
                ".div_re { padding-left: 10px;position: relative;height: 100%;font-size: 9pt; } " +
                ".div_title { text-align:center;font-size: 12pt; } " +
                ".table_ab { margin-top: 25px; } " +
                ".tx1 { width:6% ;text-align: center; } " +
                ".tx2 { width:13% ;text-align: center; } " +
                ".tx3 { width:16% ;text-align: center; } " +
                ".tx4 { width:17% ;text-align: center; } " +
                ".tx5 { width:10% ;text-align: left; } " +
                ".tx6 { width:15% ;text-align: left; } " +
                ".tx7 { width:20% ;text-align: left; } " +
                "</style></head>" +
                "<body>" +
                "<div class=\"div_re\">" +
                "<div class=\"div_title\">" + vo.getSupplierName() + " 发货单</div>" +
                "<table>" +
                "<tr>" +
                "<td class=\"tx5\" >收货商户：" + vo.getCustomerAddressVo().getName() + "</td>" +
                "<td class=\"tx5\" >收货人：" + vo.getCustomerAddressVo().getName() + "</td>" +
                "<td class=\"tx6\" >收货地址：" +
                vo.getCustomerAddressVo().getProvinceName() + vo.getCustomerAddressVo().getCityName() +
                vo.getCustomerAddressVo().getCountyName() + vo.getCustomerAddressVo().getAddress() +
                "</td>" +
                "</tr>" +
                "<tr>" +
                "<td class=\"tx5\" >下单时间：" + vo.getCreateTime() + "</td>" +
                "<td class=\"tx5\" >打印时间：" + printTime + "</td>" +
                "<td class=\"tx6\" >配送时间：</td>" +
                "</tr>" +
                "<tr>" +
                "<td class=\"tx5\" >收货人电话：" + vo.getCustomerAddressVo().getMobile() + "</td>" +
                "<td class=\"tx5\" >承运商：</td>" +
                "<td class=\"tx6\" >订单备注：" + remark + "</td>" +
                "</tr>" +
                "</table>" +
                "<table class=\"print_paper table_first\">" +
                "<tr>" +
                "<td class=\"tx1\" >序号</td>" +
                "<td class=\"tx2\" >商品编号</td>" +
                "<td class=\"tx4\" >商品名称</td>" +
                "<td class=\"tx2\" >下单数</td>" +
                "<td class=\"tx2\" >出库数</td>" +
                "<td class=\"tx2\" >单价</td>" +
                "<td class=\"tx2\" >出库金额</td>" +
                "<td class=\"tx2\" >备注</td>" +
                "</tr>" +
                goods +
                "<tr>" +
                "<td class=\"tx1\" >合计</td>" +
                "<td class=\"tx2\" ></td>" +
                "<td class=\"tx4\" ></td>" +
                "<td class=\"tx2\" ></td>" +
                "<td class=\"tx2\" ></td>" +
                "<td class=\"tx2\" ></td>" +
                "<td class=\"tx2\" ></td>" +
                "<td class=\"tx2\" ></td>" +
                "</tr>" +
                "</table>" +
                "<table>" +
                "<tr>" +
                "<td class=\"tx6\" >下单金额：￥" + MoneyUtils.changeF2Y(payAmount) + "</td>" +
                "<td class=\"tx6\" ></td>" +
                "<td class=\"tx5\" ></td>" +
                "<td class=\"tx5\" >出库金额：￥" + MoneyUtils.changeF2Y(payAmount) + "</td>" +
                "</tr>" +
                "</table>" +
                "<table class=\"table_ab\">" +
                "<tr>" +
                "<td class=\"tx6\" >收货人签名：</td>" +
                "<td class=\"tx6\" >送货人签名：</td>" +
                "<td class=\"tx6\" >发货人：</td>" +
                "<td class=\"tx5\" >发货单位盖章：</td>" +
                "</tr>" +
                "</table>" +
                "</div>" +
                "</body>" +
                "</html>";

        return str;
    }

}
